角度服务到app配置

时间:2015-12-19 22:34:15

标签: javascript angularjs

app.js

        angular
            .module('yelp',['ngRoute'])  //creating  module
            .config(config);

        config.$inject=['$routeProvider','YelpService']; //YelpService is unknown here
        function config($routeProvider){

            $routeProvider
                .when('/restaurants',{
                    templateUrl:'partials/restaurants.html',
                    controller:'RestaurantsController',
                    controllerAs:'rstrntsCtrl',
                    resolve:{
                        getRestaurants:getRestaurants
                    }
                });
        }

        function getRestaurants(YelpService){
            // i need route params here
        }

YelpService.js

    angular
        .module('yelp')  //using already created module
            .factory('YelpService',YelpService);

    YelpService.$inject=['$http'];
    function YelpService($http){

        var factory={
        }

        return factory;
    }

我首先加载了app.js文件,然后加载了yelpService.js文件。由于稍后加载服务,我认为无法注入。如果我首先加载服务文件,它会导致错误,因为在配置文件中创建了模块。如何克服这一点。此外,在配置文件中如何获取 getRestaurants 方法

中的routeparams

1 个答案:

答案 0 :(得分:1)

对于yelp使用提供者调用YelpServiceProvider。 对于解决方案,只需包装一个函数并注入所需的功能。

angular
        .module('yelp',['ngRoute'])  //creating  module
        .config(config);

    config.$inject=['$routeProvider','YelpServiceProvider']; //YelpService is unknown here
    function config($routeProvider){

        $routeProvider
            .when('/restaurants',{
                templateUrl:'partials/restaurants.html',
                controller:'RestaurantsController',
                controllerAs:'rstrntsCtrl',
                resolve:{
                    restaurants:function($routeParams, YelpService) {
                      return getRestaurants($routeParams, YelpService);
                    }
                }
            });
    }

    function getRestaurants($routeParams, YelpService){
        // i need route params here
    }

Resolve用于解析您的数据。所以左手赋值不是你可能想要的函数名,而是项目的变量列表(实际上是一个承诺)。

然后在注入“餐馆”之后在你的控制器中:

this.restaurants; // or $scope.restaurants if you are not using controllerAs