简体   繁体   中英

Angular2 Update View on async model update

I've got a Angular2 component with dependency on a datastore. Template has some databinding on that store, eg "{{datastore.weather.curTemp}}" Datastore get's updated from time to time via http.

Now i understand that this works in an asnyc way - which is the cause my curTemp get's not updated automatically when new data arrives, right?

My current solution would be to use an EventEmitter to notify my component on changes, but then I would need either a local variable to bind to, which could get messy, if I need a lot of variables from my datastore, or I would call detectChanges() on ChangeDetectorRef.

Am I on the right track? Or am I missing a simple way of populating my asny-data?

Thank you!

A way to solve your problem would be to make weather a Subject :

datastore.service.ts

public weather: Subject<any> = new Subject(); // better make this private and expose it `asObservable` via a getter nethod

updateWeather(){
  http.get(...).subscribe(res => this.weather.next(res.json()))
}

You could then get a reference to that in your component.ts:

public weather$: Observable<any>;
constructor (dataStore: DataStore){
  this.weather$ = dataStore.weather;
}

And use it in your template like this:

{{(weather$ | async).curTemp}}

That way you also don't need to handle subscriptions when your component is destroyed as the async pipe does it for you.

If your component is not updating, perhaps your async thread is running outside the NgZone, and you might need to update your component by making the assignment inside the component's NgZone .

import {Component, NgZone} from "@angular/core";

@Component({
  selector: 'app',
  templateUrl: './app.component.html'
})

export class MyComponent {
  myValue: string;

  constructor(private ngZone: NgZone) {
  }

  getData() {
    const self = this;
    myAsyncCall().then(result => {
      ngZone.run(() => {
        self.myValue = result;
      });
    });
  }
}

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