I want to call a http api and load the data using ChangeDetectionStrategy.OnPush. I know how to go about it using the ChangeDetectorRef by calling detectchanges(). The main component calling the Service is:
ngOnInit() {
this.invigilateService.getPhoto(this.email).subscribe((photo) => {
this.photo = photo;
if (this.photo.photo) {
this.image = this.sanitizer.bypassSecurityTrustUrl(this.photo.photo);
}
this.imageLoaded = true;
this.cdr.detectChanges();
});
}
The invigilateService.ts is calling the http service:
getPhoto(email: string): Observable<Photo> {
return this.http.get<Photo>(this.uri.getPhotoUri().replace('{email}',email))
.pipe(
tap(_ => console.log('fetched photo')),
catchError(this.handleError<Photo>('getPhoto', {}))
);
}
Now this works just fine. But my question is if there is a better way to do this? I keep hearing that we shouldn't really use changedetectionref markforCheck() or detectChanges() since its being manually called. I do not want to use async pipe since i can't trap errors in case the http response fails.