gpt4 book ai didi

angularjs - 在加载资源之前等待 promise 解决

转载 作者:行者123 更新时间:2023-12-04 10:39:18 25 4
gpt4 key购买 nike

我的 AngularJS Controller 之一包含这一行:

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
}),
...
}

applicationsService.getCurrentApp() 自己进行 $http 调用。因此,您或许可以看到问题所在——在 fetchAppId() 返回时,此调用可能尚未解决。

我怎样才能解决这个问题?

最佳答案

假设从 applicationsService 返回的数据通过异步方式是:

var data = [{
"PreAlertInventory": "5.000000",
"SharesInInventory": "3.000000",
"TotalSharesSold": "2.000000"
}];
applicationsService工厂返回 promise :
.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()
$scope.data = 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;
}
}
});
演示 Fiddle

关于angularjs - 在加载资源之前等待 promise 解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19585456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com