我BehaviorSubject
在我的一项服务中创建了一个,并使用asObservable稍后进行订阅,但是在控制器被销毁后我需要取消订阅,我该如何取消订阅。
服务
import { Observable, BehaviorSubject } from 'rxjs';
private currentStepObject = new BehaviorSubject<number>(0);
public currentStepObservable = this.currentStepObject.asObservable();
constructor(
) { }
public changecurrentStep(step: number): void {
this.currentStepObject.next(step);
}
控制者
import { ReaderService } from '../../../../services/reader/reader.service';
constructor(
private readerServices: ReaderService
) { }
ngOnInit() {
this.initDocumentData();
this.readerServices.currentStepObservable
.subscribe((step) => {
this.currentStep = step;
});
}
ngOnDestroy() {
}
尝试将takeUntil与有用的内部Subject一起使用。
更新:在这种情况下,您不必手动取消订阅组件中的每个订阅,因为其中可能包含多个订阅。
import { ReaderService } from '../../../../services/reader/reader.service';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators'
export class MyComponent implements OnInit, OnDestroy {
private unsubscribe$: Subject<any> = new Subject<any>();
constructor(
private readerServices: ReaderService
) { }
ngOnInit() {
this.initDocumentData();
this.readerServices.currentStepObservable.pipe(
takeUntil(this.unsubscribe$)
)
.subscribe((step) => {
this.currentStep = step;
});
}
ngOnDestroy() {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句