简体   繁体   English

Angular 4 Rxjs 主题订阅不起作用

[英]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订阅

  1. Task is started from tasks page, which is tasks.component.ts任务从任务页面开始,即tasks.component.ts
  2. Switch to other page and pause task from footer component.从页脚组件切换到其他页面并暂停任务。 It doesn't work它不起作用
  3. It works when I don't use unsubscribe.当我不使用取消订阅时它会起作用。 but if unsubscribe is not used, subscribe calls multiple time.但如果不使用取消订阅,订阅调用多次。

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 .如果您需要先前推送到可观察的值,您可以使用BehaviorSubjectReplaySubject 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM