How to assign data returned from $ promise global variable

I have two services, service1 and service2and I would like to call the method service1in service2.

Ideally, I would like to assign the returned data from a service1.getMethod()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`
});

Ideally, I would like to use what will be resultin service2'sanother functions i.e. result[0].name, etc. Not sure if what I'm doing is the right approach.

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

Thank!

+4
source share
1 answer

, . result , . getMethod2 , then:

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

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

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

:

.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);
    });
});
+5

All Articles