Reputation: 593
I am using async pipe in view, to load data dynamically in the view. However, It is not loading any data.
I need to change values of observables, few times in a page, like reload page, load more values, and change news content based on the categories of the news.
I used ChangeDetectorRef, detectChanges(), but without any luck.
ngOnInit() {
if (this.isFirstRun) {
this.items$ = this.apiService.getNewsByCategory(
this.categoryId = (this.categoryId === 0 ? 1 : this.categoryId));
this.cg.detectChanges();
}
}
//NgOnChanges
ngOnChanges(changes: SimpleChanges) {
if (this.isFirstRun) {
const chg = changes.categoryId;
this.items$ = this.apiService.getNewsByCategory(chg.currentValue);
this.cg.detectChanges();
}
}
// In the views i used these things
<div *ngIf="(items$| async) as news ; else loading">
// View stuff here
</div>
items$ must reload while any change is detected, i.e. CategoryId is chages. It is not working in this case.
However, ngOnInit is working fine.
Any help is much appreciated, No ideas is generating in my head.
Upvotes: 0
Views: 458
Reputation: 11345
There is a better pattern towards your problem, i.e use a separate subject
as a trigger and you don't need to manually detect changes for async pipe to work
refreshItems$ = new Subject()
items$ = this.refreshItems$.asObservable().pipe(
switchMap(param => this.apiService.getNewsByCategory(param)))
constructor() { }
ngOnInit() {
if (this.isFirstRun) {
this.refreshItems$.next()
}
}
ngOnChanges(changes: SimpleChanges) {
if (this.isFirstRun) {
this.refreshItems$.next(changes.categoryId)
}
}
Upvotes: 1
Reputation: 61
If the default change detector didn't detect your change, then it will not invoke ngOnChanges. So if that is your case, then you can manually check for changes using ngDoCheck.
Upvotes: 0