Angularjs - 从http get url返回的编辑数组

时间:2017-10-20 18:43:32

标签: angularjs url

我有这个数组我正在通过以下方法:

      var url= *url defined here*;
      $scope.ViewProfile = function () {
        $http.get(url)
            .success(function (response) {
                $scope.ProfileList = response;
                $scope.FavNumbers = $scope.ProfileList[0].FavNumbers;
             })
            .error(function () {
               });
    }

我需要在UI上编辑Fav Numbers列表。并通过http post url方法将其发回另一个url。我所困扰的是异步调用的概念,因此我无法检索最喜欢的数字列表以供编辑。请帮忙!

我尝试过使用promises的方法如下:

       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未定义'。它不断给出某种错误,调试器进入无限循环或其他什么。

1 个答案:

答案 0 :(得分: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;
  });
}]);

这就是你需要做的一切。