簡體   English   中英

AngularJS-Promise解決和更新視圖

[英]AngularJS - Promise resolve and update view

我正在嘗試使用ES6 Promise(獲取)解析值從其控制器更新角度視圖。 問題是當我的諾言解決時,Angular不會更新視圖,這是可以理解的。 這是一種廣播應用程序。 這是代碼。

控制器:

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.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服務將使您對所做的更改有所了解。

我不推薦這種解決方案。 我認為您應該使用$http promises避免留下角度范圍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM