【发布时间】:2019-10-26 00:17:34
【问题描述】:
我已订阅 ReplaySubject 并尝试在 ngOnDestroy 方法中取消订阅。当我离开订阅组件并返回到同一个组件而不发出数据时,它再次被订阅。请问我该如何解决这个问题?
Shared.service.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();
}
【问题讨论】:
-
你的意思是你第二次没有得到
startedEditing的值? -
它正在获取旧值?
-
是的,它的价值已经过时了
-
我第二次加载组件而不发出值,但它正在被订阅