Subscribing to Observable Input

后端 未结 2 931
温柔的废话
温柔的废话 2021-02-14 01:04

Is there a way to subscribe to an Observable which is an @Input?

For example:

export class MyComponent implements OnInit {
  @Inp         


        
2条回答
  •  星月不相逢
    2021-02-14 01:15

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

    export class MyComponent implements OnChanges {
      @Input() results: Observable;
    
      constructor() { }
    
      ngOnChanges(changes){
          if(changes["results"] && this.results){
              this.results.subscribe(value => ...);
          }
      } 
    }
    

    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.

提交回复
热议问题