angularjs - how to inject factory into another factory in Angular -
i have 2 modules , factories in both, , need implement factory first module module.
angular.module('apis', []) .value ("myvalue" , "12345") .factory('apiurl',['config','url',apiurl]) function apiurl(config,url){ } angular.module('users.service', ['apis']) .factory('userservice',['myvalue',userservice]) function userservice(apiurl,myvalue){ //login function function login(){ console.log('myvalue',myvalue) console.log('loginurl',apiurl) } return { login:login } }
notice: no problem when inject myvalue, problem in apis factory
and log:
error: [$injector:unpr] http://errors.angularjs.org/1.5.0/$injector/unpr?p0=urlprovider%20%3c-%20url%20%3c-%20apiurl%20%3c-%20userservice @ error (native)
and sorry english.
i this:
- if create
factory
useangular.module('app').factory()
. if createservice
useangular.module('app').service()
- always try have same module name. easier later, when have big application, because of dependency injection.
- try keep files separately, , concatenate later, example using
gulp
gulp-concat
- try keep configuration in
app.js
file and, when concatenating file, remember, file should on top. - i keep values , constants in
app.js
file or create new filefactory
orservice
, include it, same injected below.
app.js
(function () { 'use strict'; var app = angular.module('app', [ // other module ]); app.value('myvalue', '12345'); app.constant('myconst', 'some_constant'); app.config(['$interpolateprovider', function ($interpolateprovider) { $interpolateprovider.startsymbol('[['); $interpolateprovider.endsymbol(']]'); }]); }());
factory.js
(function () { 'use strict'; angular .module('app') .factory('apiurlfactory', apiurlfactory); apiurlfactory.$inject = []; function apiurlfactory() { var self = this; self.url = 'some_url'; return self; } }());
service.js
(function () { 'use strict'; angular .module('app') .service('userservice', userservice); userservice.$inject = ['apiurlfactory', 'myvalue']; function userservice(apiurlfactory, myvalue) { var self = this; self.login = function () { console.log('myvalue', myvalue); console.log('loginurl', apiurlfactory.url); }; return self; } }());
if have more questions, not hesitate contact me. try angular style guide https://github.com/johnpapa/angular-styleguide lot.
Comments
Post a Comment