订阅可观察的输入

订阅可观察的输入

本文介绍了订阅可观察的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以订阅@InputObservable?

例如:

export class MyComponent implements OnInit {
  @Input() results: Observable<string[]>;
  constructor() {
     this.results.subscribe(value => ...);
  }
}

在此示例中,我无法订阅可观察对象,因为它是null ...

In this example I can't subscribe to the observable because it is null...

推荐答案

您应该实现OnChanges并在输入更改时订阅.

You should implement OnChanges and subscribe to the input when it changes.

export class MyComponent implements OnChanges {
  @Input() results: Observable<string[]>;

  constructor() { }

  ngOnChanges(changes){
      if(changes["results"] && this.results){
          this.results.subscribe(value => ...);
      }
  }
}

这将使您可以在Observable可用时进行订阅,并在Observable参考发生更改时重新订阅.您可能需要根据用例考虑取消订阅旧实例.

This will allow you to subscribe to the Observable once it is available and re-subscribe to it anytime that the Observable reference changes. You may need to consider unsubscribing from old instance depending on your use-case.

这篇关于订阅可观察的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 14:41