[英]Angular 4 Rxjs subject subscribe is not working
I have a shared service data.service.ts
which have我有一个共享服务
data.service.ts
public pauseProjectTask$: Subject<any> = new Subject<any>();
pauseTaskProject(taskData,type){
this.pauseProjectTask$.next(taskData);
}
and I have a footer.component.ts
which shows currently active task in each pages, task can be paused from footer component.我有一个
footer.component.ts
,它显示每个页面中当前活动的任务,任务可以从页脚组件暂停。 I have a pause function in footer.我在页脚中有一个暂停功能。
pauseTask(taskData,type){
console.log(taskData,type);
this.pauseTaskSub = this.dataService.pauseTaskProject(taskData,type);
}
and I have other component which lists all tasks.我还有其他组件列出所有任务。
task.component.ts
. task.component.ts
。 it listens for task status change.它侦听任务状态变化。
this.pauseProjectTaskSub = this.dataService.pauseProjectTask$.subscribe(taskData => {
this.changesTaskStatus('','pause',taskData);
});
ngOnDestroy(){
this.pauseProjectTaskSub.unsubscribe();
}
its unsubscribed OnDestroy
.其取消订阅
OnDestroy
。
when I call pauseTaskProject()
which is in footer component it calls pauseTaskProject()
in data.service.ts当我打电话
pauseTaskProject()
这是在页脚组件调用pauseTaskProject()
在data.service.ts
pauseTaskProject
is called but it didn't subscribe in tasks.component.ts
pauseTaskProject
被调用,但它没有在tasks.component.ts
订阅
Give the lack of information, most probably the subscription is triggered after the function this.dataService.pauseTaskProject(taskData,type)
is called.由于缺乏信息,很可能在调用函数
this.dataService.pauseTaskProject(taskData,type)
后触发订阅。 Subscriptions to Subject
observable emit notifications that are pushed to it only after the subscription.订阅
Subject
observable 会发出通知,这些通知仅在订阅后推送给它。
If you need the previously pushed value to the observable, you could either use BehaviorSubject
or ReplaySubject
.如果您需要先前推送到可观察的值,您可以使用
BehaviorSubject
或ReplaySubject
。 I'll illustrate with ReplaySubject
with buffer size 1. It'll hold/buffer the previously pushed value to it and emit it immediately upon subscription.我将使用缓冲区大小为 1 的
ReplaySubject
进行说明。它将保存/缓冲先前推送到它的值,并在订阅后立即发出它。
import { ReplaySubject } from 'rxjs';
public pauseProjectTask$: ReplaySubject<any> = new ReplaySubject<any>(1);
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.