简体   繁体   English

更改Angular2异步管道的订阅

[英]Change subscription of Angular2 Async Pipe

I have a case where I'm using an async pipe in a angular2 component and passing an observable to it. 我有一种情况,我在angular2组件中使用异步管道并将可观察到的管道传递给它。 That works fine. 很好

What I want is later, while the component is still 'alive', ie: OnDestroy has not been called (hence async pipe is subscribed), to unsubscribe from that observable and subscribe to another. 我想要的是稍后,当组件仍处于“活动状态”时,即:尚未调用OnDestroy(因此已订阅了异步管道),以取消订阅该可观察对象并订阅另一个。

How can I achieve this ? 我该如何实现?

Here's some pseudo code to expose this case : 这是一些伪代码来暴露这种情况:

@Component({
  selector: 'pack',
  template: `
    <wolf *ngFor="let wolf of pack | async">
      ...
    </wolf>
  `
})
export class PackComponent implements DoCheck {

    pack;

    constructor(){
      this.pack = Observable.of(northwesthernWolves: Wolf[])
    }

    onDoCheck() {
      if(some condition) {
        this.pack = Observable.of(redWolves: Wolf[])
      }
    }
}

Considering that the framework has been released, it is safe to assume that it already takes care of this. 考虑到该框架已经发布,可以安全地假设它已经解决了这一问题。 And actually, it is so : 实际上是这样的

...
if (obj !== this._obj) {
  this._dispose();
  return this.transform(obj);
}
...

When new observable is assigned to class property, the old one is unsubscribed automatically by async pipe. 当将新的observable分配给class属性时, async管道将自动取消订阅旧的observable。

The opposite behaviour would lead to memory leaks and could be considered a bug. 相反的行为会导致内存泄漏,并且可以认为是错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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