//服务内部PService
this.getPTypes = function(){
var types = PTypesFactory.get({});
return types.$promise.then(function(result)
{
console.log(result.groups);
return result.groups;
});
}
// Controller 内部
$scope.groups = PService.getPTypes();
控制台日志显示正确获取的 REST 数据,但是当我这样做时
console.log($scope.groups);
我明白
Object {then: function, catch: function, finally: function}
这是 Promise API,而不是正确解析的数据。
最佳答案
问题在于您尝试像使用同步函数一样使用异步函数。
then
是一个返回 Promise 的方法。
当使用回调调用它时,回调不会立即调用,只有当响应从服务器返回时才调用。
你可以这样写:
服务
this.getPTypes = function(callback){
PTypesFactory.get({}).then(callback);
}
Controller
PService.getPTypes(function(res){
$scope.groups = res.data;
});
关于javascript - Controller 内的变量未解析为由 Promise 解析的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21313209/