简体   繁体   中英

AngularJS - Promise resolve and update view

I am trying to update an angular view from its controller using an ES6 Promise (fetch) resolved value. The thing is Angular does not update the view when my promise resolves, which is understandable tbh. This is a kind of radio app. Here's the code.

Controller:

angular.module('myApp').controller('MyCtrl', [
  'myPlayer', 'radio', function(player, radio) {

    // Some initilization

    this.next = function() {
      this.currentSong = this.upcomingSong;
      radio.nextSong().then(song => {
        this.upcoming = song;
      });
    };

and my view looks like this:

<img ng-src="{{player.upcomingSong.imgUrl}}" alt="{{player.upcomingSong.name}}">
<div>
    <p>{{player.upcoming.title}}</p>
    <p>{{player.upcoming.artist}}</p>
</div>

I've searched through the documentation and several questions and articles, but those seemed more complicated than they should be, cause I think I am missing something fundamental.

What is the proper way of implementing this?

Thanks.

By using the ES6 promise, you're leaving the angular scope. That means that angular doesn't know something has changed inside his component.

What you can do is

angular.module('myApp').controller('MyCtrl', [
  'myPlayer', 'radio', '$timeout', function(player, radio, $timeout) {

    // Some initilization

    this.next = function() {
      this.currentSong = this.upcomingSong;
      radio.nextSong().then(song => {
        $timeout(() => {
          this.upcoming = song
        }, 0);
      });
    };

Using the $timeout service will make angular know about the change you made.

I'm not recommending this solution. I think you should rather use $http promises to avoid leaving angular scope.

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