首页 > 解决方案 > 无法退订 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();
}

标签: angularangular6angular7

解决方案


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$您提供的代码中永远不会更新。你能简化并且只使用一个吗?


推荐阅读