angularjs - Can't redefine service defined as constant -
here temp.js
angular.module('temp', []) .service('tempfactory', function() { this.a =10; });
and here 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 property', function() { console.log(tempfactory.a); });
});
in console value of 20.
but if define tempfactory this:
angular.module('temp', []) .constant('tempfactory', { a: 10; });
in console value of 10.
why can't redefine tempfactory defined constant, can redefine tempfactory defined service, value or factory?
because when create service, provide constructor function it
.service('tempfactory', function() { this.a = 10; })
angular creates instance of function kinda this:
var tempfactoryinstance = new tempfactory(); return tempfactoryinstance;
and returns instance, access a
property right away.
but constant not anything, returnes you've passed it, so
.constant('tempfactory', function() { this.a = 10; })
will return function you. if want able access property a
in situation, have "instantiate" it:
var instance = new tempfactory(); console.log(instance.a); // 10
see plunker.
you can read more behavior of different provider in documentation.
Comments
Post a Comment