I'm trying to pass async data (an observable) from a parent to child component, but it seems the changes are not being updated on the child component and I'm not sure why.
I have a (simplified) service that is using BehaviourSubject
:
@Injectable()
export class MyService {
private _items: BehaviorSubject<any[]> = new BehaviorSubject([]);
public items: Observable<any[]> = this._items.asObservable();
list() {
this.http.get('...').subscribe(items => {
this._items.next(items);
})
}
}
(The list()
function is being called regularly from elsewhere in my app to update the data.)
I then have a parent component:
@Component({
selector: 'parent',
templateUrl: '<child [items]="myService.items | async"></child>',
})
export class Parent {
constructor(public myService: MyService) {
}
}
and a child:
@Component({
selector: 'child',
templateUrl: '<ul><li *ngFor="item of _items">{{item.name}}</li></ul>',
})
export class Parent implements OnChanges {
@Input() items;
_items = [];
constructor() {
}
ngOnChanges(changes: SimpleChanges) {
console.log('changes', changes);
this._items = changes.items;
}
}
My understanding is that using the async
automatically subscribes/unsubscribes to my Observable and passes any new data down to my child component. When new data comes in, my child component should detect those changes in ngOnChanges
and print them out.
- My console output is never firing, indicating that no changes are being detected in the child. I've manually subscribed to the Observable in my parent component to verify that new data is coming in so I'm not sure where I'm going wrong here.
- Is this the correct was to deal with asynchronous data at the component level?
list()
function from my service and this seems to be the real underlying problem. I would imagine it's to do with the function being called outside of the Angular run loop (or something similar) – Timmy O'Mahony