2017-10-20 156 views
0

我有這樣的陣列,我通過以下方法得到恢復。並通過http post url方法將其發回到另一個網址。我卡住的是異步調用的概念,因此我無法檢索最喜歡的數字列表以供編輯。請幫忙!Angularjs編輯陣列從HTTP GET URL

我試圖用承諾的方法如下:

 app.factory('myService', function($http) { 
     var myService = { 
     async: function(url) { 
     var promise = $http.get(url).then(function (response) { 
      console.log(response); 
      return response.data; 
     }); 
     // Return the promise to the controller 
     return promise; 
    } 
}; 

    return myService; 
}); 

在我的控制器中我做:

angular.module('JuryApp').controller('mycontroller', ['myService', function (myService) { 

     myService.async(url).then(function(d) { 
    $scope.data = d; 
}); 

    app.controller('MainCtrl', function(myService,$scope) { 
    // Call the async method and then do stuff with what is returned inside  our own then function 
    myService.async().then(function(d) { 
    $scope.data = d; 
    }); 
}); 

但我不斷收到錯誤「d沒有定義」。它不斷給出某種錯誤,調試器進入一個無限循環或某處。

回答

0

我覺得你太過於複雜了。異步調用實際上是非常簡單的:

你服務:

app.factory("myService", ["$http", function($http) { 
    var MyService = { 
    getData: function(url) { 
     return $http.get(url); //$http returns a promise by default 
    } 
    }; 
    return MyService; 
})]; 

你的控制器:

angular.module('JuryApp').controller('mycontroller', ['myService', function (myService) { 
    $scope.FavNumbers = []; 
    var url = "http://my.api.com/"; 
    myService.getData(url).then(function(response) { 
    $scope.FavNumbers = response.data[0].FavNumbers; 
    }); 
}]); 

這就是所有你需要做的。