angular - 无法退订 ReplaySubject 的订阅
问题描述
我已订阅 ReplaySubject 并尝试在 ngOnDestroy 方法中取消订阅。当我离开订阅组件并返回相同组件而不发出数据时,它再次被订阅。我可以知道如何解决这个问题吗?
共享服务.ts
import { Injectable } from '@angular/core';
import { TestCase } from './test-case-form/test-case.model';
import { Subject } from 'rxjs/Subject';
import { ReplaySubject } from 'rxjs/ReplaySubject';
@Injectable({
providedIn: 'root'
})
export class SharedService {
testCasesChanged = new Subject<TestCase[]>();
private startedEditing = new ReplaySubject<number>();
public startedEditing$ = this.startedEditing.asObservable();
setData(index) {
console.log("setData called", index);
this.startedEditing.next(index);
}
}
a.component.ts
export class TestFormComponent implements OnInit, OnDestroy {
@ViewChild('f') testForm : NgForm;
subscription: Subscription;
editIndex: number;
editMode = false;
editedTestCase: TestCase;
private testCases: TestCase[]= [];
ngOnInit() {
this.subscription = this.sharedService.startedEditing$
.subscribe((index: number) => {
console.log("Subscribed");
this.editIndex = index;
this.editMode = true;
this.editedTestCase =
this.sharedService.getTestCase(this.editIndex);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
解决方案
private startedEditing = new ReplaySubject<number>();
public startedEditing$ = this.startedEditing.asObservable();
// `startedEditing$` is no longer `startedEditing` they are now two different things
然后你做
this.startedEditing.next(index);
仅更新startedEditing
startedEditing$
您提供的代码中永远不会更新。你能简化并且只使用一个吗?
推荐阅读
- unit-testing - How to test VueRouter's beforeRouteEnter using '@vue/test-utils'?
- code-coverage - Getting llvm-cov to talk to codecov.io
- r - R plotly: Click in a graph and creates a new one or filters other
- r - 在r中将字符串组合成一个字符串
- wordpress - 为什么位置:固定在 Chrome 上不起作用?
- bash - 根据选择的选项向文件名添加或删除日期
- docker - 如何在单独的 shell 中打开 docker-compose 服务
- java - 将 Toothpick DI 框架与 Java(仅限)项目一起使用
- r - 使用 dplyr 的组的不同过滤规则
- haskell - 为什么要加入。(flip fmap) 有类型 ((A -> B) -> A) -> (A -> B) -> B?