My app needs to make a number of api requests (approximately 500) and display the data. It needs to display the results as the requests are completed. So far I have set it to use an async pipe with an observable.
I have tried putting ChangeDetectorRef.detectChanges() in the complete() function call. But the view wasn't affected in any way.
news.component.ts
export class NewsComponent implements OnInit {
news: Observable<News[]>;
temp: News[] = new Array();
constructor(private dataService: DataService, private ref: ChangeDetectorRef) {
}
ngOnInit() {
this.news = this.getData();
}
getData(): Observable<News[]> {
let newsArr = new Subject<News[]>();
this.dataService.getTopNews().subscribe(val => {
this.temp.push(val);
newsArr.next(this.temp);
}, null, () => {
newsArr.complete();
this.ref.detectChanges();
console.log(this.news); //print all fetched data
});
return newsArr.asObservable();
}
}
news.component.html
<app-news-item *ngFor="let newsItem of news | async" [news]="newsItem">
</app-news-item>
news-item.component.ts
@Component({
selector: 'app-news-item',
templateUrl: './news-item.component.html',
styleUrls: ['./news-item.component.css']
})
export class NewsItemComponent implements OnInit {
@Input() news: Subject<News>;
constructor() { }
ngOnInit() {
}
}
The view (html) is only updating once, at the beginning with just some chunks of data. The data is loading properly and complete() fires after all the data is fetched as well.