Use a $routeProvider resolve function inside anoth

2019-07-24 15:49发布

问题:

I have three resolve promise function inside my $routeProvider. My question is that Can I use getData function inside load function for example to get HTTP request response!

Also will angular wait for getData finish then goes to load? Is it doing them in order and waiting for the promises!?

$routeProvider.when = function(path, route) {
        route.resolve = {
            getData: ['$http', function ($http) {
                var http = $http({
                    method: 'POST',
                    url: 'a URL',
                    data: {
                        route: "/something"
                    },
                    headers: {
                        'something': 'anything'
                    }
                });
                return http;
            }],
            load: [
                'getData',
                function(getData) {
                    console.log(getData);
                    // I'm Actually returning a promise here so no problem at all.
                }
            ],
            prefData: [
                '$preflightService',
                function($preflightService) {
                    console.log('Preflight Run');
                    return $preflightService.run();
                }
            ],
        };
        return originalWhen(path, route);
    };

Using this code above I get this Error in Console

Error: [$injector:unpr] http://errors.angularjs.org/1.4.12/$injector/unpr?p0=getDataProvider%20%3C-%20getData

What should I do?!

Should I define a provider somehow!?

回答1:

Each resolve is resolved asynchronously. If you want the data returned by 'getData' for resolving the 'load' request, make it a single resolve, something like this:

loadData: ['$http', function($http) {
      return $http({
        method: 'POST',
        url: 'a URL',
        data: {
          route: "/something"
        },
        headers: {
          'something': 'anything'
        }
      }).then(function(response){
        // getData result available here
        return // Return the load promise here
      });
    }

If needed, you can attach a success handler (.then(function(){}) to the load promise and return a custom object containing both getData results and load results like

return {
 getData: getResp,
 loadedData: loadResp
}

which will be available in the controller.