Use a $routeProvider resolve function inside another one

旧巷老猫 提交于 2020-01-05 03:35:44

问题


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.



来源:https://stackoverflow.com/questions/39219448/use-a-routeprovider-resolve-function-inside-another-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!