简体   繁体   中英

How to subscribe Input property to call out function Angular 2+

Hi I have an issue like in subject: My Parent component passes the value to his child component like this:

<em-event-list  [sumListEvents]="sumListEvents"></em-event-list>

So when when value sumListEvents will change I want to subscribe that value to call out the function from Service. This is how my children component looks:

 @Input() sumListEvents: Observable<number>;
 private events: Event[] = [];

 constructor(private dataService: EventListService) { 
    let loadSubscription = this.sumListEvents.subscribe(
      value => {
        this.events = this.dataService.showEvents(value)
      }
    )
  }

But I receive error on subscribe Cannot read property 'subscribe' of undefined in the sumListEvents . Any ideas?

sumListEvents is not available at the moment you need it. You can use *ngIf to subscribe only when sumListEvents available.

<em-event-list *ngIf [sumListEvents]="sumListEvents"></em-event-list>

This will work but it might not be a best practise to pass event to the child and subscribe it in a child.

You may refer to https://scotch.io/tutorials/3-ways-to-pass-async-data-to-angular-2-child-components for other ways to pass async data to child component.

A better approach will be to use the async pipe and a setter .

<em-event-list *ngIf [sumList]="sumListEvents$ | async"></em-event-list>

 @Input() set sumList(value) {
   if(value) {
     this.events = this.dataService.showEvents(value);
   }      
 }

 private events: Event[] = [];

 constructor(private dataService: EventListService) { }

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