简体   繁体   中英

angular service into app config

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

I loaded app.js file first and then yelpService.js file. Since service is loaded later i think it is not available to inject. If i load service file first, it causes an error, since the module in created in config file. How to overcome this. Moreover in config file how to get routeparams in getRestaurants method

For yelp use the provider call YelpServiceProvider . For the resolve just wrap in a function and inject the desired functionality.

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 is used to, well, resolve your data. So the left hand assignment would not be a function name as you have perhaps meant but the variable list of items (a promise actually).

Then in your controller after having injected 'restaurants':

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM