简体   繁体   中英

angular using $http in factory

I seem to be having an issue sending json from my factory out to controllers

Here is my factory

 .factory("UserService", function($http) {
var LevelsHere;
$http.get("/assets/images/generated.json").success(function(data){
    LevelsHere = data;
    return LevelsHere;
});


    return {
        all: function() {
          return LevelsHere;
        },
        first: function() {
          return LevelsHere[0];
        }
      };
})

I am simply trying to send the json object out (or bits of it) with this factory. I can console.log inside the http get and it seems to be grabbing the json just fine. I seem to have hit a wall, any help would be much appreciated. I would just like the all ad first functions to be working. thanks!

I first had success by hard coding the levelsHere above it with the json string like var levelsHere = [{"stuff in here"}], but when i moved it over to an $http it doesn't work.

Since you don't have any $watch to look over the value returned from asynchronous $http.get request, the updated value is not available to the consumer. As $http.get request returns a promise, you can leverage the promise and update the value on success of the promise in then() as below:

var app = angular.module('app', [])
.factory("UserService", function($http) {
    var LevelsHere = $http.get("https://api.github.com/users/mralexgray/repos")
               .success(function(data){
                 return data;
               });
    return {
        all: function() {
          return LevelsHere;
        }
      };
})  
.controller('controller', function(UserService, $scope){
    UserService.all().then(function(data){
        $scope.value = data;    
    });
})

DEMO

What is not working exactly? My guess is that you got undefined immediately after this factory method, since $http uses deferred object

You are returning LevelsHere before the async call is finished. The order of your operation goes:

  1. call http.get
  2. return all and first which return LevelsHere (even though the http request has not finished)
  3. http get returns json
  4. success call back fires returning LevelsHere to nobody.

A better way is to just return the promise:

return $http.get("/assets/images/generated.json") 

then in your controller you can get the value from the promise by calling the success function. If you try to resolve the promise in the factory and return the value, your controller will try to use the value before it's returned from the server.

var promise = UserService()
promise.success(function(data){
// do something with data
}

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