Can't redefine service defined as constant

212 views Asked by At

Here is my temp.js

angular.module('temp', [])
    .service('tempFactory', function() {
        this.a =10;
    });

and here is my temp.Spec.js

describe('temp', function() {
    var tempFactory;

    beforeEach(function() {
        var mockedTempFactory = {};

        module('temp', function($provide) {
            $provide.value('tempFactory', mockedTempFactory);
        });

        mockedTempFactory.a = 20;

        inject(function(_tempFactory_) {
            tempFactory = _tempFactory_;
        });
    });

it('console.log of a property', function() {
    console.log(tempFactory.a);
});

});

In console I get value of 20.

But if I define tempFactory like this:

angular.module('temp', [])
    .constant('tempFactory', {
        a: 10;
    });

In console I get value of 10.

Why can't I redefine tempFactory which was initially defined as constant, but can redefine tempFactory which was initially defined as service, value or factory?

1

There are 1 answers

2
Michael Radionov On

Because when you create a service, you provide a constructor function to it

.service('tempFactory', function() {
    this.a = 10;
})

Angular then creates an instance of this function kinda like this:

var tempFactoryInstance = new tempFactory();
return tempFactoryInstance;

and returns back exactly that instance, so you could access the a property right away.

But the constant does not do anything, it just returnes what you've passed to it, so

.constant('tempFactory', function() {
    this.a = 10;
})

will just return a function back to you. If you want to be able to access the property a in this situation, then you have to "instantiate" it:

var instance = new tempFactory();
console.log(instance.a); // 10

See the plunker.

You can read more about the behavior of different provider in the documentation.