簡體   English   中英

未從工廠設置$ scope變量

[英]$scope variable not set from Factory

我是Angular的新手,我試圖將一些數據從工廠方法傳遞到控制器中。 登錄Factory變量時,可以看到數據。 我嘗試將數據傳遞到$ scope變量($ scope.song),但是在方法之外,$ scope變量未定義。 我究竟做錯了什么? 下面的代碼:

.controller('MessagesCtrl', function($scope, FetchSong){
FetchSong.nextSong('audio-message')
  .then(function(response){
    $scope.song = FetchSong.queue;
    console.log(FetchSong.queue);    //logs the data 
    console.log(response.data);     //also logs the data
});
console.log($scope.song);   //returns undefined
})

這是執行代碼的時間表:

// t0: ask the service for the next song: the service sends an HTTP 
// request (I guess) to get it
FetchSong.nextSong('audio-message')
  .then(function(response){

    // t0 + 3 seconds: the http message has reached the server 10,000 
    // miles away from here, the server got the next song from its 
    // database, and sent it back. It took some time to travel the 10,000
    // miles in the other direction, but it finally arrived, so we can 
    // store it in the scope
    $scope.song = FetchSong.queue;
    console.log(FetchSong.queue);    //logs the data 
    console.log(response.data);     //also logs the data
});

// t0 + 1 microsecond: try to print the next song
console.log($scope.song);   //returns undefined

要意識到的關鍵是,每當服務返回一個您在其上調用then()並傳遞回調函數的promise時,這意味着它不能立即返回該值。 它返回...一個諾言,稍后將解決,因為在獲得結果之前需要異步完成一些工作。

因此,在致電服務並獲得承諾后立即打印結果將永遠無法進行。 該結果僅在稍后調用了回調函數后才可用。

我寫了一篇博客文章,解釋了承諾如何工作以及如何避免陷入陷阱的陷阱。

問題是,您嘗試在$scope.song之前在FetchSong.nextSong回調中FetchSong.nextSong分配值,因為FetchSong.nextSong是異步的,所以與FetchSong.nextSong返回數據相關的所有代碼都應放在其回調中,請參閱doc

 .controller('MessagesCtrl', function($scope, FetchSong){

      FetchSong.nextSong('audio-message').then(function(response){

          $scope.song = FetchSong.queue;
          console.log(FetchSong.queue);    //logs the data 
          console.log(response.data);     //also logs the data

      }).then(function(){

          console.log($scope.song);   //returns FetchSong.queue

      });

 })

您應該使用$ scope。$ apply(); https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope中查看更多

暫無
暫無

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

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