Home > Enterprise >  OnPush Changedetection for a http service
OnPush Changedetection for a http service

Time:07-26

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.

CodePudding user response:

This is exactly the way it should be done.

By using ChangeDetectionStrategy.OnPush, you basically say that, for the sake of better performance, you are fine with Angular not detecting all changes for you and that you will trigger change detections manually if needed. Here it is needed, and you trigger it manually. Exactly as intended.

  • Related