简体   繁体   中英

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. 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.

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.

The opposite behaviour would lead to memory leaks and could be considered a bug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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