How do I return data from a $http.get() inside a factory in angularjs

前端 未结 3 1762
孤独总比滥情好
孤独总比滥情好 2020-12-03 11:40

I\'m having a lot of trouble with this and I can\'t seem to find anything here on SO or Google that helps me spot what I\'m doing wrong

         


        
相关标签:
3条回答
  • //in  $httpProvider.interceptors    
    if (typeof response.data === 'string') {
       return response;
    }
    else {
      return response.data;
    }
    
    0 讨论(0)
  • 2020-12-03 12:11

    Use defer:

    obj.getResponse = function(){                 
        var temp = {};
        var defer = $q.defer();
        $http.get('hello.php').success(function(data){
                alert(data);
                temp =data;
                defer.resolve(data);
    
        });
        return defer.promise;
    }
    
    0 讨论(0)
  • 2020-12-03 12:13

    What's happening here is a result of the asynchronous nature of $http.get, When you run $http.get it doesn't run in order. That is, it 'branches off' and runs along side the rest of the code. This is done to accommodate for the server latency.

    Here's a bad visualisation.

    .getResponse Called                Return Temp.
    |-------------------|--------------|
                        |---------------------------------|
                        $http.get ~Waiting for Server~    Temp assigned to data.
    

    Can you see how Temp is returned before it's been given a value?

    Thankfully, you can use what Angular calls a promise, This is a variable which you can return from a function, that gets 'resolved' later. You instantiate a promise like this.

    var myPromise = $q.defer();
    

    You assign values to it by using

    myPromise.resolve(data);
    

    You can then return this promise later in the function, in the normal way. ie.

    return myPromise.promise
    

    Of course, for all of this you need the $q library, which you include in the function parameters.

    0 讨论(0)
提交回复
热议问题