Injecting Dependencies in config() modules - AngularJS

前端 未结 4 2004
面向向阳花
面向向阳花 2020-11-29 18:45

Currently in app.js i have the following routes:

var gm = angular.module(\'gm\', [\'gm.services\',\'gm.directives\',\'gm.filters\',\'gm.controllers\',\'ngSan         


        
相关标签:
4条回答
  • 2020-11-29 19:00

    You should use constant for that, because it's the only thing you can inject in the config phase other than providers.

    angular.module("yourModule").constant("paths", {
      base: function(){ ... }
    });
    
    0 讨论(0)
  • 2020-11-29 19:01
    1. angular.config only accepts Providers
    2. every service, factory etc are instances of Provider

    So to inject a service in config you just need to call the Provider of the service by adding 'Provider' to it's name.

    angular.module('myApp')
      .service('FooService', function(){
        //...etc
      })
      .config(function(FooServiceProvider){
        //...etc
      });
    

    According to the angularjs Provider documentation

    ... if you define a Factory recipe, an empty Provider type with the $get method set to your factory function is automatically created under the hood.

    So if you have a factory (or service) such as:

    .factory('myConfig', function(){
      return {
        hello: function(msg){
          console.log('hello ' + msg)
        }
      }
    })
    

    You first need to invoke your factory using the $get method before accessing the returned object:

    .config(function(myConfigProvider){
       myConfigProvider
         .$get()
         .hello('world');
    });
    
    0 讨论(0)
  • 2020-11-29 19:10

    This discussion helped me when I was trying to figure out the same thing, basically

    $routeProvider.when('/', {
                    templateUrl:'views/main.html',
                    controller:'MainController',
                    resolve: {
                        recentPosts: ['$q', 'backendService', function($q, backendService){
                            var deferred = $q.defer();
                            backendService.getRecentPosts().then(
                                function(data) {
                                    var result = data.result;
                                    deferred.resolve(result);
                                },
                                function(error) {
                                    deferred.reject(error);
                                }
                            );
                            return deferred.promise;
                        }]
                    }
                })
    
    0 讨论(0)
  • 2020-11-29 19:18

    In .config you can only use providers (e.g. $routeProvider). in .run you can only use instances of services (e.g. $route). You have a factory, not a provider. See this snippet with the three ways of creating this: Service, Factory and Provider They also mention this in the angular docs https://docs.angularjs.org/guide/services

    0 讨论(0)
提交回复
热议问题