我在使用 $q.defer();
时遇到了一些问题
当我改用回调时,我的代码正常工作( View 已更新),但使用了$q.defer();
不是。
这是我的代码:
服务:
eventsApp.factory('eventData', function($http, $q) {
return {
getEvent: function(callback) {
var deferred = $q.defer();
$http({method: 'GET', url: '/node/nodejsserver/server.js'}).
success(function(data, status, headers, config){
//callback(data.event);
deferred.resolve(data.event);
console.log('status: ', status, ' data: ', data);
}).
error(function(data, status, headers, config){
deferred.reject(status);
console.log('status: ', status);
});
return deferred.promise;
}
};
});
Controller :
eventsApp.controller('EventController',
function EventController($scope, eventData) {
$scope.event = eventData.getEvent();
}
);
但它不起作用。
然后我找到this answer我像这样更新了我的 Controller :
eventsApp.controller('EventController',
function EventController($scope, eventData) {
eventData.getEvent().then(function(result) {
$scope.event = result;
});
}
);
并且有效。
非工作代码和工作代码之间有什么区别?
最佳答案
非工作代码使用自动 promise 展开,这在最近版本的 Angular 中已被弃用和删除。它被认为太神奇了。
当你返回一个 promise 时,Angular 过去常常做以下事情:
- 返回一个空数组。
- 稍后在请求到达时填充它。
- 自行触发摘要。
这种行为被 Angular 开发人员认为是令人困惑和神奇的,并且在 Angular 中被弃用(在 1.2 中)、停用并很快(1.3)被删除。通过 promise 分配值的正确方法就像您在第二个示例中指出的那样:
eventData.getEvent().then(function(result) {
$scope.event = result;
});
来自 Angular 1.3(待定)发布文档:
$parse: due to fa6e411d, promise unwrapping has been removed. It has been deprecated since 1.2.0-rc.3. It can no longer be turned on. Two methods have been removed:
来自 1.2 版本文档:
$parse and templates in general will no longer automatically unwrap promises.
Before:
$scope.foo = $http({method: 'GET', url: '/someUrl'});
<p>{{foo}}</p>
After:
$http({method: 'GET', url: '/someUrl'})
.success(function(data) {
$scope.foo = data;
});``
{{foo}}
`This feature has been deprecated. If absolutely needed, it can be reenabled for now via the $parseProvider.unwrapPromises(true) API.
当我们在这里时,避开 the deferred anti pattern , $http
已经返回 promise ,所以你可以简单地 return
它而不是使用 $q.defer
.
关于javascript - AngularJs $q.defer() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25463411/