Javascript 使用';解决';在routeProvider中等待查询结果的步骤
我很难弄清楚如何让routeProvider等到远程呼叫返回。到目前为止,我看到的最佳解决方案是以下示例: . 不幸的是,当我疲于将该示例应用于自己的代码时,绑定将在数据实际加载之前触发。有人知道另一个使用angular 1.1.5中新资源语法的例子吗(promise可以直接访问) 下面是我的代码的样子:Javascript 使用';解决';在routeProvider中等待查询结果的步骤,javascript,angularjs,promise,angularjs-routing,Javascript,Angularjs,Promise,Angularjs Routing,我很难弄清楚如何让routeProvider等到远程呼叫返回。到目前为止,我看到的最佳解决方案是以下示例: . 不幸的是,当我疲于将该示例应用于自己的代码时,绑定将在数据实际加载之前触发。有人知道另一个使用angular 1.1.5中新资源语法的例子吗(promise可以直接访问) 下面是我的代码的样子: var productModule = angular.module('productModule', ['ngResource', 'ngLocale']). config(['$route
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"]);
}]);
如果我运行该代码,控制台将显示:
- 呼叫服务
- 承诺已解决
- 呼叫成功
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' });
});