Promise dependency resolution order in angular ui-router

前端 未结 4 937
野性不改
野性不改 2020-12-15 06:11

I have set up a top-level controller that is instantiated only when a promise (returned by a Config factory) is successfully resolved. That promise basically do

4条回答
  •  没有蜡笔的小新
    2020-12-15 06:51

    I agree with you that the resolves should chain, and I've hit many problems around this area.

    However, they don't, so the solution I have come up with is to use my own promise stored in a service which you resolve when the data is complete. I have tried my best to edit your plunkr to work but to no avail. I am no longer hitting your errors though, so hopefully you can work from this: http://plnkr.co/edit/Yi65ciQPu7lxjkFMBKLn?p=preview

    What it's doing:

    Store the config in a state alongside a new promise object

    myapp.service('state', function($q) {
      this.load = $q.defer();
      this.config = {}
    })
    

    On your first resolve, store your config in this service and once ready resolve the new promise we created above.

    myapp.factory('Config', function($http, $log, state) {
      return $http.get('example.json')
        .then(function (data) {
          angular.extend(state.config, data.data);
          state.load.resolve();
        });
    });
    

    The final and most important step is to not call our second the content of the childs resolve function until after our promise above is resolved:

    myapp.factory('MyConfigDependingResource', function($log, state) {
      return state.load.promise.then(function() {
        if (!state.config.text) {
          $log.error('Config is uninitialized!');
        }
        else {
          // Do wonderful things
        }
        return
      });
    });
    

    The main thing you will need to be aware of is that the config is now stored in a state. There should be ways around this but this is how I've done it before.

提交回复
热议问题