每次初始化组件时,都从Behavior Subject接收多个数据实例 [英] Receiving multiple instances of data from Behavior Subject every time component is initialised

查看:149
本文介绍了每次初始化组件时,都从Behavior Subject接收多个数据实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的路由器,在其中我正在调用服务并从行为主题接收数据...当我导航到另一条路线并卷土重来时,我正在从主题接收多个值...我该如何销毁所有一个主题的观察者,并在需要时创建新主题...?这是插件示例 http://plnkr.co/edit/OKiljCekSKHO1zJF5MAy?p=preview
我打算销毁ngOnDestroy中某个主题的观察者...

I have a simple router where i am calling a service and receiving the data from the behavior Subject...When i navigate to another route and comeback i am receiving multiple values from the subject...How can i destroy all the observers of a subject and create new subject whenever i need...? Here is the plunker demo http://plnkr.co/edit/OKiljCekSKHO1zJF5MAy?p=preview
I am planning to destroy the observers of a subject in ngOnDestroy...

  ngOnDestroy(){
this.srvc.DestroySubject();
 }

有人可以告诉我如何摧毁行为主体的观察者吗?

Can somebody please tell me how to destroy the observers of a behaviorsubject?

推荐答案

预期的行为.

export class Sample1 {
  constructor(public srvc:HeroService) {
      this.srvc.Data.subscribe(data=> {
        console.log(data);
      });
      this.srvc.GetData();
  }
}

在构造函数中,您预订srvc.Data,并且由于DataBehaviorSubject,它返回最近发出的值.您用null初始化Data,因此首先没有数据.

In the constructor you subscribe to srvc.Data and because Data is a BehaviorSubject it returns the most recent emitted value. You initialize Data with null, therefore at first there is no data.

然后在构造函数中调用this.srvc.GetData(),这将导致事件发出并被订阅(前面的行)接收.

Then in the constructor you call this.srvc.GetData() this causes an event to be emitted and be received by the subscription (the lines before).

如果您导航离开并返回,则Sample1会再次初始化并执行构造函数.第一件事是订阅srvc.Data.并从上次调用GetData()(当我们第一次导航至Heroes时)获得最后发出的值Received Data.

If you navigate away and back, then Sample1 is initialized again and the constructor is executed. The first thing is that is subscribes to srvc.Data. and it gets the last emitted value which is Received Data from the previous call to GetData() (when we first navigated to Heroes).

接下来的事情是对this.srvc.GetData()的调用,该调用再次发出Received Data,并且订阅将传递此值.

The next thing is the call to this.srvc.GetData() which again emits Received Data and the subscription gets this value passed.

解决方法

要解决此问题,您可以将呼叫移至this.srvc.GetData();到服务,而不是像

To fix it you could move the call to this.srvc.GetData(); to the service instead like

@Injectable()
export class HeroService {
  Data: BehaviorSubject<RepairOrder> = new BehaviorSubject(null);

  constructor() {
    this.GetData();
  }

  GetData(){
    this.Data.next('Recieved Data');
  }
  DestroySubject(){
    //alert('hi');
  }
}

柱塞示例

这篇关于每次初始化组件时,都从Behavior Subject接收多个数据实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆