Simple-Solution
Simple-Solution

Reputation: 4289

How to assign data returned from $promise to global variable

I've two services, service1 and service2, and I would like to invoke a method of service1 into service2.

Ideally, I would like to assign the returned data from service1.getMethod() to a global variable declared as var result = [].

Here is the code:

service1

.factory('service1', function (dependencies...) {
    var getMethod1 = function () {
       ...//making http get call
       return deferred.promise();
    };

    return {
       getMethod1 : getMethod1
    };
});

service2

.factory('service2', function (dependencies...) {
    var result = [];

    var getMethod2 = function () {
        Service1.getMethod1().then(function (data) {
            result = data;
    });

    //RUN METHOD
    getMethod2();

    //Here ideally, I would like result to contain `[object, object, object]`
    console.log(result); //instead it prints `undefined`
});

So ideally, I would like to use what's will be in result in service2's other functions i.e. result[0].name etc. Not sure if what I'm doing is the right approach.

Please provide an plunker demo or code snippet example and if not sure about something, please write comment below.

Thanks!

Upvotes: 5

Views: 3539

Answers (1)

dfsq
dfsq

Reputation: 193261

You can't work with asynchronous code like you are attempting. result variable is simply not yet populated when you are trying to use it. Instead you should make getMethod2 return promise too, and use its then method:

.factory('service2', function (dependencies...) {

    var getMethod2 = function () {
        return Service1.getMethod1();
    };

    // RUN METHOD
    getMethod2().then(function(result) {
        console.log(result);
    });
});

You can also cache returned data:

.factory('service2', function (dependencies...) {

    var result;

    var getMethod2 = function () {
        return result ? $q.when(result) : Service1.getMethod1().then(function(data) {
            result = data;
            return result;
        });
    };

    // RUN METHOD
    getMethod2().then(function(result) {
        console.log(result);
    });
});

Upvotes: 5

Related Questions