gpt4 book ai didi

javascript - 使用 'resolve'在routeProvider中等待查询结果

转载 作者:行者123 更新时间:2023-12-02 20:25:46 25 4
gpt4 key购买 nike

我无法弄清楚如何让routeProvider等待远程调用返回。到目前为止我见过的最好的解决方案是这里的例子:delaying angular route change。不幸的是,当我厌倦了将该示例应用于我自己的代码时,绑定(bind)将在数据实际加载之前触发。有谁知道另一个使用 Angular 1.1.5 中的新资源语法的示例(可以直接访问 $promise )?

这是我的代码:

var productModule = angular.module('productModule', ['ngResource', 'ngLocale']).
config(['$routeProvider', function($routeProvider) {

$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html',
controller: 'ResourceCtrl as appController' ,
resolve:
{
productData: function($resource)
{
console.log(["calling service"]);
return $resource(Services.ProductServices.PATH).query(null,
function(data){
console.log(["call succeeded"]);
},
function(data){
console.log(["calling failed"]);
}).$promise;
}
}
});
$routeProvider.when('/view2', {templateUrl: 'partials/partial2.html'});
$routeProvider.otherwise({redirectTo: '/view1'});
}]) ;

productModule.controller('ResourceCtrl','$scope','productData',function($scope,productData) {

$scope.productData = productData;
console.log(["promise resolved"]);
}]);

如果我运行该代码,控制台将显示:

  • 调用服务
  • promise 已解决
  • 调用成功

最佳答案

它应该像这样简单:

resolve: {
productData: function(ProductServices) {
return ProductServices.query().$promise.then(function(data){
return data;
});
}
}

如果您的服务看起来像这样:

myApp.factory('ProductServices', function($resource) {
return $resource('/path/to/resource/:id', { id: '@id' });
});

关于javascript - 使用 'resolve'在routeProvider中等待查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18516965/

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