繁体   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