gpt4 book ai didi

javascript - 我如何使用 $q all angular.js 处理多个 http 请求

转载 作者:行者123 更新时间:2023-11-30 05:48:43 26 4
gpt4 key购买 nike

我正在尝试围绕 $q angular 库进行思考。在我的路由提供者中,我想从服务器获取所有数据并将其存储在 localStorage 中。但出于某种原因,解析似乎不等待所有 http 请求在路由到 selectMedia 之前完成。根据我阅读 Angular 文档的理解,这应该可以工作,但事实并非如此。我是完全误解了这个概念还是我的想法是对的?

         $routeProvider.           
when('/', {
redirectTo : '/selectMedia',
resolve: {
data: function ($q, backendApi, localStorage, network, route, loginService){
var prices = function () {
var defer = $q.defer();
backendApi.prices.get(function (data) {
localStorage.setItem("videoPrice", data.VideoPrice);
localStorage.setItem("imagePrice", data.ImagePrice);
localStorage.setItem("prices", data.SliderPrices);
localStorage.setItem("priceSuffix", data.PriceSuffix);
defer.resolve();
}, defer.resolve);
return defer.promise;
};
var validFormats = function () {
var defer = $q.defer();
backendApi.validFormats.get(function (formats) {
localStorage.setItem("validFormats", formats);
defer.resolve();
}, defer.resolve);
return defer.promise;
};
var videoFormats = function () {
var defer = $q.defer();
backendApi.videoFormats.get(function (videoFormats) {
localStorage.setItem("videoFormats", videoFormats);
defer.resolve();
}, defer.resolve);
return defer.promise;
};
var categories = function () {
var defer = $q.defer();
backendApi.categories.get(function (data){
localStorage.setItem("categories", data.Categories);
defer.resolve();
},defer.resolve);
return defer.promise;
};
var renewToken = function () {
var defer = $q.defer();
loginService.renewToken(defer.resolve);
return defer.promise;
};

if(network.isOnline()){
var promises = [renewToken(), categories(), videoFormats(), validFormats(), prices()];
return $q.all(promises);
}
else if(!network.isOnline() && localStorage.length === 0){
route('/error');
}
}
}
});
}]);

最佳答案

我没有看到路由定义中指定的路由 Controller 。我猜你已经在 View 级别通过 ngController 设置了它。当您没有在定义中指定 Controller 时,将跳过 resolve block 。

4/23 更新

从官方文档中提取的resolve属性的定义:

An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, they will be resolved and converted to a value before the controller is instantiated and the $routeChangeSuccess event is fired.

根据定义,resolve 属性的设计目的是有一种方法可以将依赖项注入(inject)与路由关联的 Controller 。

关于javascript - 我如何使用 $q all angular.js 处理多个 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16150371/

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