我是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()
并传递回调函数,这意味着它不能现在就返回值。它返回……一个稍后将被解决的承诺,因为在结果可用之前需要异步完成一些工作。
因此,在调用服务并获得承诺返回后立即打印结果将永远不起作用。结果只有在回调函数被调用后才可用。
我写过一篇博文,解释承诺是如何工作的,以及如何避免像你掉进的陷阱。
问题是,在FetchSong.nextSong
承诺回调中被赋值之前,您尝试访问$scope.song
,因为承诺是异步的,所有与承诺返回数据相关的代码都应该放在回调中,参见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