Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular ui-router nested resolves are not resolving

I have nested ui-views which are both waiting on data from http request. In the following code i have simulated this with timeouts. If i set the timeouts any longer than 10 ms then my plunker wont load at all.

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);
  }
});

The services are defined as follows.

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
  }
}]);

I need service2 to wait until service 1 returns its data in order to fulfill its request.The way I have it set up does not seem to work. What have I done wrong? If there is a better way to set up my app any suggestions are appreciated. I have modified the ui-view nested view demo plunker her: plnkr

like image 879
David Pace Avatar asked Jan 11 '23 09:01

David Pace


1 Answers

Have a read of how hierarchical resolves work:

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

You don't need to wait for service 1 to complete inside service 2, but rather inject the results from the parent resolve into the child resolve function.

like image 186
Matt Way Avatar answered Jan 15 '23 11:01

Matt Way