无法取消订阅ReplaySubject的订阅

时间:2019-06-11 14:28:32

标签: angular angular6 angular7

我已经订阅了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();
}

2 个答案:

答案 0 :(得分:0)

您在ngOnDestroy处的退订。

您正在使用组件中的旧值,因为您使用的是ReplaySubjectReplaySubject缓存与它一起发出的所有值。因此,每次您订阅该主题时,都会针对您为此ReplaySubject发出的每个值调用您的subscription方法。

可以通过以下方式更改缓冲区大小:

// Only the last emitted value is cached and emitted to every new subscriptions
private startedEditing = new ReplaySubject<number>(1); 

如果只想获取最后发出的值,也可以使用BehaviourSubject

但是我想您只想使用一个简单的Subject

答案 1 :(得分:0)

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$从未在您提供的代码中更新。您可以简化并只使用一个吗?