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

pbu*_*eit 2 javascript promise angularjs angularjs-routing

我无法弄清楚如何让routeProvider等到远程调用返回.我见过的最好的解决方案是这里的例子:延迟角度路线变化 .不幸的是,当我厌倦将该示例应用于我自己的代码时,绑定将在数据实际加载之前触发.有没有人知道另一个使用角度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"]);
}]);
Run Code Online (Sandbox Code Playgroud)

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

  • 呼叫服务
  • 承诺解决了
  • 呼叫成功

Val*_*mer 10

它应该像这样简单:

resolve: {
  productData: function(ProductServices) {
    return ProductServices.query().$promise.then(function(data){
      return data;
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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