can't get service instance from $injector.get()

前端 未结 1 1108
盖世英雄少女心
盖世英雄少女心 2021-02-05 12:51

I define a customer service named \"greeting\", but can\'t get the instance from $injector.get(\'greeting\'). It will throw such error: Unknown provider: greetingProvider &l

相关标签:
1条回答
  • 2021-02-05 12:59

    You need to create the injector from the module.

    var app = angular.module('myDI', []);
    app.config(function($provide){
        $provide.provider('greeting', function(){
            this.$get = function(){
                 return function(name) {
                     console.log("Hello, " + name);
                };
            };
        });
    });
    var injector = angular.injector(['myDI', 'ng']); //Add this line
    var greeting = injector.get('greeting');
    greeting('Ford Prefect');
    var injector = angular.injector();
    

    Try it here. FIDDLE

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