I am confused by what is happening in a section of my app. I have a component that uses ngOnChanges. ngOnchanges fires right before ngOnInit when the component loads. Both ngOnChanges and ngOnInit call a certain method (fetchResults) that calls an api service to get some data using an observable return. I have a tap
on my call to the service to console log the returned data and also a breakpoint in vs for the api method that gets called.
When the initial call to fetchResults
is made from the ngOnChanges
hook, the service does not return any data and the api breakpoint is not hit. However, when the ngOnInit
hook is triggered and the fetchResults
is called a second time, the api breakpoint is hit and the console log displays the returned data.
Why is this happening? I am expecting any call to fetchResults
to hit the api and return data. I have validated that the required param is being passed. The call from ngOnChanges
and the the call from ngOnInit
are identical.
Sample code:
ngOnInit() {
console.log('fetchResults called from ngOnInit')
this.fetchResults(this.itemId);
}
ngOnChanges(changes: SimpleChanges) {
console.log('ngOnChanges called with changes value: ', changes)
this.fetchResults(changes['propName'].currentValue)
}
fetchResults(itemId){
console.log('fetchResults function called with competitionId: ', itemId)
this.resultList$ = this.dataservice.getResults(itemId)
.pipe(
map( result => {
return result.map(
item => {
return item;
}
)
}),
tap(val => console.log(' fetchResults function - the value of returned result object: ', val))
)
}
Result Component Html with async binding:
... this.resultList$ | async" ...