Angularjs 正在等待在加载资源之前解析承诺
我的一个AngularJS控制器包含以下行:Angularjs 正在等待在加载资源之前解析承诺,angularjs,promise,Angularjs,Promise,我的一个AngularJS控制器包含以下行: api.tickets.query() api模块包含以下内容: angular.module('myapp.api', [ 'ngResource' ]) .factory('api', function($resource, applicationsService) { function fetchAppId() { return applicationsService.getCurrentApp(); } ret
api.tickets.query()
api
模块包含以下内容:
angular.module('myapp.api', [
'ngResource'
])
.factory('api', function($resource, applicationsService) {
function fetchAppId() {
return applicationsService.getCurrentApp();
}
return {
tickets: $resource('tickets', {
applicationId: fetchAppId
}),
...
}
ApplicationService.getCurrentApp()本身进行$http调用。因此,您也许可以看到问题所在—在fetchAppId()返回时,此调用可能尚未解决
我怎样才能避开这个问题呢?你需要做的就是给自己一个承诺
.factory('api', function($resource, applicationsService,$q) {
function fetchAppId() {
return applicationsService.getCurrentApp();
}
return {
tickets: function() {
var defer=$q.defer();
fetchAppId().then(function(data) {
var appId=data;
$resource('tickets', {applicationId: appId})
.then(function(data) {
defer.resolve(data);
})
}
return defer.promise;
}
}
假设通过异步方式从
ApplicationService
返回的数据是:
var data = [
{
"PreAlertInventory": "5.000000",
"SharesInInventory": "3.000000",
"TotalSharesSold": "2.000000"
}
和ApplicationService
工厂退货承诺:
.factory('applicationsService', ['$resource','$q', function($resource, $q) {
var data = [
{
"PreAlertInventory": "5.000000",
"SharesInInventory": "3.000000",
"TotalSharesSold": "2.000000"
}
];
var factory = {
getCurrentApp: function () {
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
}
return factory;
}]);
我只需要调用api.tickets()
但是我们的api
服务看起来像:
.factory('api', function($resource, applicationsService,$q, $timeout) {
function fetchAppId() {
return applicationsService.getCurrentApp();
}
return {
tickets: function() {
var deferred=$q.defer();
fetchAppId().then(function(data) { // promise callback
$timeout(function(){ // added dummy timeout to simulate delay
deferred.resolve(data);
}, 3000);
});
return deferred.promise;
}
}
});
演示如果要在路线更改之前等待角度资源(
$resource
)解析,则需要返回$promise
$routeProvider.when('/tickets', {
resolve: {
'tickets': function ('Ticket') {
// do this to resolve the async call prior to controller load
return Ticket.query().$promise;
// this will resolve 'tickets' during/after controller load
return Ticket.query();
}
},
controller: ...
});
答对了,谢谢,马克西姆,这很有魅力。欣赏这些细节:)我认为这是有效的,因为$scopes中的承诺是等待$apply()循环完成的。正如文档所述,“$q与$rootScope.Scope模型观察机制集成在angular中,这意味着更快地将分辨率或拒绝传播到模型中,并避免不必要的浏览器重新绘制,这将导致UI闪烁。”如果有人使用$resource请求,然后我们需要包括$PROMITE fetchAppId().$PROMITE.then(函数(数据){--});
$routeProvider.when('/tickets', {
resolve: {
'tickets': function ('Ticket') {
// do this to resolve the async call prior to controller load
return Ticket.query().$promise;
// this will resolve 'tickets' during/after controller load
return Ticket.query();
}
},
controller: ...
});