nuruddin February 2016

how to inject factory into another factory in Angular

I have two modules and factories in both, and I need to implement factory from the first module into another 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 I inject myValue, but the problem in APIs Factory

and my log:

Error: [$injector:unpr] http://errors.angularjs.org/1.5.0/$injector/unpr?p0=urlProvider%20%3C-%20url%20%3C-%20apiUrl%20%3C-%20userService at Error (native)

and sorry for my English.

Answers


ssuperczynski February 2016

I would do it like this:

  1. If you create factory use angular.module('app').factory(). If you create service use angular.module('app').service()
  2. Always try to have same module name. It is easier later, when you have big application, because of dependency injection.
  3. Try to keep files separately, and concatenate it later, for example using gulp gulp-concat
  4. Try to keep all you configuration in app.js file and, when you concatenating file, remember, this file should be on top.
  5. I would keep values and constants in app.js file or would create new file like factory or service and include it, same as I injected it 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', api 

Post Status

Asked in February 2016
Viewed 3,357 times
Voted 6
Answered 1 times

Search




Leave an answer