Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

It is possible to call a method with no parameters on this simple subscribe?

  • A SHORT DESCRIPTION

Im using an observable on my code, i want to keep it clean as posible and i need to call detectChanges() method to update *ngIf= on html.

  • QUESTION

Is there any way to call detectChanges() method on subscribe() similar to the example below?

Example (not working because overload):


this.subscriptions.add(
  this._hotelEffect
    .getHotel()
    .pipe(map(this.createHotel))
    .subscribe(this._changes.detectChanges)
);

My best resolution at the moment:


this.subscriptions.add(
  this._hotelEffect
    .getHotel()
    .pipe(
      map((resp) => {
        this.createHotel(resp);
        this._changes.detectChanges();
      })
    )
    .subscribe()
);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Is that what you mean?

this.subscriptions.add(
  this._hotelEffect
    .getHotel()
    .pipe(map(this.createHotel.bind(this)))
    .subscribe(()=>this._changes.detectChanges())
);

assuming that this.createHotel can consume a return type of getHotel()

i want to keep it clean as posible and i need to call

If this is really the case, then I would do it like this

  this._hotelEffect
    .getHotel()
    .subscribe((resp) => {
        this.createHotel(resp);
        this._changes.detectChanges();
      });

Also since you have stated that you collect subscriptions to cancel them on component destruction – there is a better and cleaner way to do it using takeUntil operator

  //field 
  private onDestroy=new Subject();
  ngOnDestroy(){ onDestroy.next();onDestroy.complete()}
   
  //and then with ANY observable in the component
  this._hotelEffect
    .getHotel()
    .pipe(takeUntil(this.onDestroy))
    .subscribe((resp) => {
        this.createHotel(resp);
        this._changes.detectChanges();
      });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading