0

I could not make it persistent behavior in HTML part while using subscribe to the http client in the Anglar 9. I tried following stackoverflow posts -

  1. Angular 2 View will not update after variable change in subscribe
  2. Angular 6 View is not updated after changing a variable within subscribe

Following is the code what I am trying

export class BaseComponent implements OnInit, OnDestroy {
  list: any[];
  unsubscribe$: Subject<any> = new Subject();

  constructor(private ngZone: NgZone,private changeRef: ChangeDetectorRef) {
 
  }

  ngOnInit(): void {
     return this.http
            .get(environment.apiBaseUrl + url, this.getOptions())
            .pipe(takeUntil(this.unsubscribe$))
            .subscribe(()=>{
                this.ngZone.run(()=>{
                   this.list = response.data;
                })
                this.list = response.data;
                this.changeRef.detectChanges();
                this.changeRef.markForCheck();
            });

  }

  ngOnDestroy(): void {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }


}

// Nothing working for me.


  
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Veshraj Joshi
  • 3,544
  • 3
  • 27
  • 45

2 Answers2

2

Your onInit function should be like this, if you use onPush strategy:

 ngOnInit(): void {
     return this.http
            .get(environment.apiBaseUrl + url, this.getOptions())
            .pipe(takeUntil(this.unsubscribe$))
            .pipe(retry(3), catchError(this.handleError));
            .subscribe(response => {
                this.list = response.data;
                this.changeRef.markForCheck();
            });

  }
Anton Marinenko
  • 2,749
  • 1
  • 10
  • 16
2

I think u should make ur life easier by using async pipes.

ngOnInit(): void {
    let urURl = 'https://reqres.in/api/products';
     this. list$ = this.http
            .get(urURl)

  }

app.component.html

{{list$|async|json}}

I have created a demo for u on stackblitz

hanan
  • 1,768
  • 1
  • 14
  • 19
  • will try and let you know – Veshraj Joshi Jul 05 '20 at 07:18
  • thanks, code you suggested also worked but in project above pattern is being used. And i do not see how to prevent memory leak.Anyway you deserve upvote. – Veshraj Joshi Jul 05 '20 at 08:23
  • @VeshrajJoshi if u are looking not to leak memory then async is the best u don't have to manage subscriptions, its doing it own it own. u just have to give ur observable. – hanan Jul 05 '20 at 15:13