AngularJS-承诺解决和更新视图



我正在尝试使用ES6 Promise(Fetch)解析值从其控制器更新其控制器。问题是,当我的承诺解决时,Angular不会更新视图,这是可以理解的TBH。这是一种无线电应用。这是代码。

控制器:

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;
      });
    };

我的观点看起来像这样:

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

我已经搜索了文档以及几个问题和文章,但是这些问题似乎比应该复杂,因为我认为我缺少一些基本的东西。

实施此操作的正确方法是什么?

谢谢。

通过使用ES6 Promise,您要离开角范围。这意味着Angular不知道他的组件内发生了变化。

您可以做的是

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);
      });
    };

使用$timeout服务将使您所做的更改了解Angular。

我不建议使用此解决方案。我认为您宁愿使用$http承诺避免离开角范围。

最新更新