简体   繁体   中英

Angular $http success deprecated amendments

I am following a book on creating an App using the MEAN stack. I have come to a point where I have followed the code exactly but I am getting an error because the book uses an old version of Angular before they removed the $http success method. I would like to continue my learning from the book but am having trouble editing the code to use the new .then version of $http. I currently have

 var locationListCtrl = function ($scope, loc8rData) {
  $scope.message = "Searching for nearby places";
   loc8rData
     .success(function(data) {
       $scope.message - data.length > 0 ? "" : "No locations found";
      $scope.data = { locations: data };
     })
     .error(function (e) {
      $scope.message = "Sorry, Something's gone wrong";
   });
};

 var loc8rData = function ($http) {
  return $http.get('/api/locations?lng=-0.79&lat=51.3&maxDistance=20');
 };

I have looked on this site and have found that I need to change this to the new way of using $http which is

$http(...)
  .then(function onSuccess(response) {
   // Handle success
   var data = response.data;
   ...
 }).catch(function onError(response) {
   // Handle error
   var data = response.data;
   ...
 });

I'm a bit of a newbie so apologies if this is obvious but I'd like to know how to exactly amend the code so I can continue with the book tutorial. In particular I don't understand the ... in $http(...) Thanks

It looks like the ellipses are just placeholders (ie "Implement your code here..."), not to worry. Anyways, the .then() gets called when the Promise for data resolves.

$http.get('https://www.google.com')
    .then(function(response) {
        console.log('Got response: ', response);
    })
    .catch(function(error) {
        console.log('Got an error: ', error);
    });

Specifically, in your code snippet:

var locationListCtrl = function ($scope, loc8rData) {
  $scope.message = "Searching for nearby places";
  return loc8rData
    .then(function(data) {
      $scope.message = data.length > 0 ? "" : "No locations found";
      $scope.data = { locations: data };
    })
    .catch(function(e) {
      $scope.message = "Sorry, Something's gone wrong";
    });
};

var loc8rData = function ($http) {
  return $http.get('/api/locations?lng=-0.79&lat=51.3&maxDistance=20');
};

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