Sandra Willford
Sandra Willford

Reputation: 3789

angularjs: passing a service into another service?

I am trying to sort out the best way to do the following:

At the request of our backend developer we want to have a json file that contains a master list of the api urls that are used in requests by my frontend. This way the end user's browser only makes one request for the object and we can then pass them this into other services. so for example...

the dataUrl JSON contains the following

{
    "emails":"json/emails.json",
    "mapping":"json/mapping.json",
    "profile":"json/profile.json"
}

and I would need to store that as a variable that could be used in all of my api calls like such:

app.factory('Emails', ['$http', function($http, Urls) {

    var url = ""; //something here to get the dataUrl object for "emails"

    var query = {};
    query.getItems = function () {
        return  $http.get(url.emails); //from var emails above?
    };
    return query;
}]);

What is going to be my best approach to this?

This is what I tried so far and it didn't work...

app.factory('Urls', ['$http', function($http) {
    var query = {};
    query.getItems = function () {
        return  $http.get('json/dataUrls.json');  
    };
    return query;
}]);

app.factory('Emails', ['$http', function($http, Urls) {
    Urls.getItems().then(function(response) {
        var url = response.data.emails;
        console.log(url);
    })
    var query = {};
    query.getItems = function () {
        return  $http.get('json/emails.json');  
    };
    return query;
}]);

This results in a console error TypeError: Cannot read property 'getItems' of undefined

Upvotes: 0

Views: 30

Answers (1)

Saurabh Agrawal
Saurabh Agrawal

Reputation: 7739

You are injecting dependency in wrong way

First inject it then create it's instance

Try this

Replace

app.factory('Emails', ['$http', function($http, Urls) {

to

app.factory('Emails', ['$http', 'Urls', function($http, Urls) {

Upvotes: 1

Related Questions