Krishh
Krishh

Reputation: 4231

Understanding provider in Angularjs

I am very new to angularjs and I am trying to understand the basics. Can anyone explain me why some of the values were undefined in the below example.

(function () {
'use strict';

    var app = angular.module('app', []);

    app.constant('configuration', {
        CONSTANT: "This is from constant",
    });

    app.provider('test',['configuration', function (configuration) {
      this.testItem1 = configuration.CONSTANT + "+ TestItem1";

      this.$get=['configuration', function(configuration){
        return {
          testItem2: configuration.CONSTANT + "+ TestItem2"
        }
      }];
    }]);

    app.config(['testProvider', function (tp) {
        console.log("From app.config: " + tp.testItem1);
        console.log("From app.config:" + tp.testItem2); //undefined
      }
    ]);

    app.run(['test', function(test){
        console.log("From app.run:" + test.testItem1); //undefined
        console.log("From app.run:" + test.testItem2);
    }]);
})();

Also I have a question on the life cycle or flow. I am assuming this is how it flows. app.config->DI test provider->DI configuration-constant->app.run. Please correct me if I am wrong. Thank you.

Plunkr demo: http://plnkr.co/edit/2TIqgxMxBJEPbnk2Wk6D?p=preview

Upvotes: 0

Views: 56

Answers (1)

Minko Gechev
Minko Gechev

Reputation: 25682

There is a difference between provider and service.

Provider is a an object, which has a $get method, i.e. when you use:

app.config(['testProvider', function (tp) {
    console.log("From app.config: " + tp.testItem1);
    console.log("From app.config:" + tp.testItem2); //undefined
  }
]);

tp is:

  this.testItem1 = configuration.CONSTANT + "+ TestItem1";

  this.$get=['configuration', function(configuration){
    return {
      testItem2: configuration.CONSTANT + "+ TestItem2"
    }
  }

On the other hand, when you use:

app.run(['test', function(test){
    console.log("From app.run:" + test.testItem1); //undefined
    console.log("From app.run:" + test.testItem2);
}]);

tp is:

{
   testItem2: configuration.CONSTANT + "+ TestItem2"
}

Upvotes: 1

Related Questions