简体   繁体   中英

Angular 2 view not updated after API call

I have a angular2 component, inside of which I have a method that populates data from API call by calling service method.

getData() {
  this.someBinding = "Initial value";
  this.someService.get('some url').then(() => {
    this.someBinding = "Updated Value";
   }
  ).catch(//error handling)
} 

I call getData() method inside ngOnInit() lifecycle hook like this:

ngOnInit(){
  this.getData();
}

Problem is, inside view {{someBinding}} is not updated after API call is finished. I get data properly in my API call, but binding not updated.

I found solution to manually fire change detection ( this.cdr.detectChanges() ) after data has arrived inside getData().then(), which is working just fine.

I am not able to identify what the problem is in this case, why I need to fire change detection manually. I have not found the reason but solution just works fine. Please explain.

You dont need to convert an observable to a promise, you're better off using the observable directly.

service:

getData(): Observable<Something> {
  return this.http.get(...)
}

component:

ngOnInit() {
  this.someBinding = this.service.getData();
}

component template:

{{ someBinding | async }}

Angular can render observables directly in the view using async. It will also automatically unsubscribe when the component is destroyed. It's best to stick with the Observable API as it is used throughout the Angular application

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM