AngularJS - Injecting a Provider

我只是一个虾纸丫 提交于 2019-12-07 08:24:26

I can see two mistakes in your code:

1) You cannot inject 'myProvider' in your application module since 'myProvider' is defined in your application module.

2) The name of 'myProvider' is wrong, Angular automatically append 'Provider' to your provider.

Here is the fix:

1) Define your provider in a dedicated module and add this new module in your application module dependencies.

2) Rename your provider to 'my' (or inject 'myProviderProvider' in your config function) :

angular.module('myProviderModule', [])
    .provider('my', function () { // or 'myProvider'

        // Private variables
        var salutation = 'Hello';

        // Private constructor
        function Greeter() {
            this.greet = function () {
                return salutation;
            };
        }

        // Public API for configuration
        this.setSalutation = function (s) {
          salutation = s;
        };

        // Method for instantiating
        this.$get = function () {
            return new Greeter();
        };
    });

angular.module('myApp', [
    'ngRoute',
    'myProviderModule'
])
.config(function ($routeProvider, myProvider) { // or 'myProviderProvider'
    $routeProvider
        .when('/', {
            templateUrl: 'views/main.html',
            controller: 'MainCtrl'
        })
        .otherwise({
            redirectTo: '/'
        });
});

See this fiddle: http://jsfiddle.net/Z3k2s

You are confusing provider with modules. Modules include set of providers, services and factories.

You also should NOT add provider suffix when defining a provider, or else you have to inject it like myProviderProvider.

Also you look like you are confusing the syntax on angular.module:

// create a new module foo.bar with dependency to ngRoute
angular.module('foo.bar', ['ngRoute']);

// create a new module woo.hoo with NO dependency
angular.module('woo.hoo', []); 

// get already created module foo.bar
angular.module('foo.bar')

Your code fixed:

'use strict';

angular.module('someModule', [])
  .provider('my', function () {

    // Method for instantiating
    this.$get = function () {
      return {}// return something
    };
  });



'use strict';

angular.module('myApp', [
        'ngRoute',
        'someModule'
    ])
    .config(function ($routeProvider, myProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'views/main.html',
                controller: 'MainCtrl'
            })
            .otherwise({
                redirectTo: '/'
            });
    });

You are attempting to load a dependent module named myProvider:

angular.module('myApp', [
        'ngRoute',
        'myProvider'
    ])

myProvider is already in the myApp module, so you can do this:

angular.module('myApp', [
        'ngRoute'
    ])
    .config(function ($routeProvider, myProvider) {
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!