mohi666
mohi666

Reputation: 7032

Cannot get $get method called automatically in angularjs provider

Here's the piece of code I'm writing in angularjs 1.5.5:

export default angular.module(
  'myApp', [])
  .provider('finder', function finderProvider() {
    this.$get = $get;

    function $get() {
      console.log('GET');
    }

    this.callMe = () => {
      console.log('CALLED');
    };
  })
  .config(['finderProvider', function(finderProvider) {
    //finderProvider.$get();
    finderProvider.callMe();
  }])
  .name;

I'm trying to inject a service into this provider later. I read on documentation that I can only inject a service inside a provider using $get() method. However, I cannot call $get() automatically. The only way I can get this working is to call $get() manually in the section where I commented the call. But it doesn't seem right to me to call $get manually.

In this example only 'CALLED' is getting logged. Any idea what I'm missing here?

EDIT. I tried to use another syntax using the arrow function, but got the same result:

.provider('finder', () => {
    return {
      $get: () => {
        console.log('GET');
      },
      callMe: () => {
        console.log('CALLED');
      }
    };
  })

Thanks in advance.

Upvotes: 0

Views: 821

Answers (1)

Estus Flask
Estus Flask

Reputation: 222354

Angular services are lazily instantiated.

Service provider constructor function is called when it is injected during config phase (config block or other provider).

$get is called when service instance is injected after config phase.

In the example above finder service isn't injected anywhere, service instance isn't created and $get function isn't called.

Upvotes: 2

Related Questions