简体   繁体   English

Angular $http 成功弃用修正

[英]Angular $http success deprecated amendments

I am following a book on creating an App using the MEAN stack.我正在关注一本关于使用 MEAN 堆栈创建应用程序的书。 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.我已经到了完全遵循代码的地步,但是我收到一个错误,因为这本书在删除 $http 成功方法之前使用了旧版本的 Angular。 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.我想继续从这本书中学习,但在编辑代码以使用 $http 的新 .then 版本时遇到问题。 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 的新方式,即

$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特别是我不明白 $http(...) 中的 ... 谢谢

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.无论如何,当数据的Promise解析时, .then()会被调用。

$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');
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM