如何解决路径变更中子控制器的承诺?

时间:2015-04-01 15:20:28

标签: angularjs angular-ui-router ionic-framework ionic angular-promise

我有一个Angular Ionic应用程序。我在其路线中分配了控制器,模板及其解决方案。这工作正常,以便我的主控制器仅在父控制器的所有承诺解决后加载。 但是如果这个路由包含另一个带有一些承诺的子控制器。这里的问题是页面只需要在父和子控制器的所有承诺解决后加载。

Punker

var app = angular.module('testApp', ['ionic']);

app.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider.state('dashboard', {
      url: "/dashboard",
      templateUrl: "dashboard.html",
      controller: 'DashboardController',
      title: 'Dashboard',
      resolve: {
          UserDetails: function(DataService) {
              return DataService.getUserDetails(1);
          },
          DashboardDetails: function(DataService) {
              return DataService.getDashboardDetails();
          }
      }
  });

  $urlRouterProvider.otherwise('/dashboard');
});

app.factory('DataService', function($q) {
   return {
     getUserDetails: function(id){
       var defer = $q.defer();
       var userDetails = {
         name: "Saidh"
       }
       defer.resolve(userDetails);
       return defer.promise;
     },
     getDashboardDetails: function(){
       var defer = $q.defer();
       var dashboardDetails = {
         title: "Dashboard"
       }
       defer.resolve(dashboardDetails);
       return defer.promise;
     }
   }
});

app.controller('HeaderController', function($scope, UserDetails) {
   console.log(UserDetails);//Error: [$injector:unpr] Unknown provider:
   $scope.userDetails = UserDetails;
});
app.controller('DashboardController', function($scope, DashboardDetails) {
   console.log(DashboardDetails);//Working: show result
   $scope.dashboardDetails = DashboardDetails;
});

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

简单添加嵌套状态,每个州都应拥有自己的resolve: somePromise属性here i fork your plunkr并添加超时,以便父视图和子视图仅为promisesolved

时显示

示例:

    $stateProvider.state('header', {
      url: "/home",
      templateUrl: "header.html",
      controller: 'HeaderController',
      resolve: {
          UserDetails: function(DataService) {
              return DataService.getUserDetails(1);
          }
      }
  });

  $stateProvider.state('header.dashboard', {
      url: "/dashboard",
      controller: 'DashboardController',
      templateUrl: "dashboard.html",
      parent: 'header',
      resolve: {
          DashboardDetails: function(DataService) {
              return DataService.getDashboardDetails();
          }
      }
  });

这是非常具有战略意识的前锋

答案 1 :(得分:0)

你只能在DashboardController内得到解决方案的承诺,你永远不会在html模板内的家庭控制器内得到它。 路由器state本身提到的控制器内部提供了解析服务。因此,您可以访问DashboardController中的依赖项,将其置于范围变量&使它可用于子范围并查看。

此外,您需要从UserDetails移除HomeController依赖项以消除错误,因为UserDetails永远无法访问

<强>代码

app.controller('DashboardController', function($scope, DashboardDetails, UserDetails) {
  console.log(UserDetails); //Working: show result
  $scope.dashboardDetails = DashboardDetails;
  $scope.userDetails = UserDetails;
});

请参阅Working Plunkr此处