Adriano
Adriano

Reputation: 924

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?

Upvotes: 0

Views: 468

Answers (2)

Bazinga
Bazinga

Reputation: 11234

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) { }

Upvotes: 0

Jecfish
Jecfish

Reputation: 4189

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.

Upvotes: 1

Related Questions