简体   繁体   中英

get out data from promise function in angular

I have this service file part of angular project , issue is I cant back value to main function from promise.then function .. here is the code

angular.module('starter.services', [])

.factory('Services', function ($http,$q) {

    var def = $q.defer();
  // Might use a resource here that returns a JSON array
    $http.get('JSONFILE').then(function (data) {
        def.resolve(data.data);
    });


this.result ={};
    var var1 = def.promise;
            var1.then(function (data){
                this.result = data;
                console.log(this.result);
            });

    // Some fake testing data
  console.log(this.result);

        return {
            all: function () {
                return var1;
            },
            remove: function (service) {
                var1.splice(var1.indexOf(service), 1);
            },
            get: function (serviceId) {
                for (var i = 0; i < var1.length; i++) {
                    if (var1[i].id === parseInt(serviceId)) {
                        return var1[i];
                    }
                }
                return null;
            }
        };

});

this.result will return empty object outside promise.then but get right data inside it.

Actually, if you are talking about this log statement here:

// Some fake testing data
console.log(this.result);

The reason why this.result doesn't have the same data is because the Promise is probably still pending (fulfilling the promise).

I suspect when you see these console logs, you see the one outside the Promise display first. This is to be expected.


Also, your block scope is different, meaning this.result can be different inside that Promise context.

Try changing:

this.result = {};

to:

var result = {};

And also change

var1.then(function (data){
    result = data;
    console.log(result);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM