angular ui-router嵌套解析没有解析

时间:2014-01-25 23:32:51

标签: angularjs angular-ui-router

我有嵌套的ui-views,它们都在等待来自http请求的数据。在下面的代码中,我用超时模拟了这个。如果我将超时设置为超过10毫秒,那么我的掠夺者根本不会加载。

var myapp = angular.module('myapp', ["ui.router"])
myapp.config(function($stateProvider, $urlRouterProvider){

  // For any unmatched url, send to /route1
  $urlRouterProvider.otherwise("/route1")
  try{
  $stateProvider
  .state('contacts', {
    templateUrl: 'contacts.html',
    controller: function($scope, service1){
        $scope.title = service1.getData()
    }
    ,resolve:{
      titlePromise:function(service1){
      return service1.myPromise
    }}
  })
  .state('contacts.list', {
    templateUrl: 'contacts.list.html',
    controller: function($scope, service2){
        $scope.contacts = service2.getData();
    },
    resolve:{
      contactPromise:function(service2){return service2.myPromise}
    }
  });
  }catch(e){
    alert.log(e);
  }
});

服务定义如下。

myapp.factory('service1',['$q', function($q){
  var title = 'Not Yet';
  var _promise = $q.defer();
  setTimeout(function(){

    title='My Contacts';
    _promise.resolve(true);
  },100);

  return {
    getData:function(){return title},
    myPromise: _promise.promise
  }
}]);

myapp.factory('service2',['$q','service1', function($q, service1){

  var data =  [];
  var _promise = $q.defer();
  setTimeout(function(){
    service1.myPromise.then(function(){
      data=[{ name: 'Alice' }, { name: 'Bob' }];
      _promise.resolve(true);
    })
  },100);
  return{
    getData:function(){return data},
    myPromise:_promise
  }
}]);

我需要service2等到服务1返回其数据才能完成其请求。我设置它的方式似乎不起作用。我做错了什么?如果有更好的方法来设置我的应用程序任何建议表示赞赏。我修改了ui-view嵌套视图demo plunker her:plnkr

1 个答案:

答案 0 :(得分:9)

阅读分层结算的工作原理:

https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views#wiki-what-do-child-states-inherit-from-parent-states

您不需要等待服务1来完成服务2内部,而是将父解析的结果注入子解析功能。