AngularJS версии 1.6 меняется с метода `.success` на метод `.then`

на самом деле я следую весеннему учебнику. Придя к Angularjs, он использует .succes

var app=angular.module("MyApp",[]);
.controller("MyController",function($scope,$http){
    $scope.pageProduits=null;

    $http.get("http://localhost:8080/chercherProduits?mc")
    .success(function(data){
         $scope.pageProduits=data;
    })
    .error(function(err){
         console.log(err);
    });

});

теперь моя проблема в том, что успех не работает, и после поиска я обнаружил, что методы .success и .error устарели и были удалены из AngularJS 1.6. вместо этого я должен использовать стандартный метод .then. Может ли кто-нибудь преобразовать существующий код в код с помощью метода then? Я пытался, но у меня не получилось, может ли кто-нибудь помочь, пожалуйста, я не знаком с javaScript? Спасибо


person Rania El'Oueslati    schedule 20.03.2017    source источник
comment
.then(ответ) => .catch(ошибка) => .finally()   -  person tenderloin    schedule 20.03.2017


Ответы (4)


До

$http(...).success(function onSuccess(data, status, headers, config) {
  // Handle success
  //...
}).error(function onError(data, status, headers, config) {
  // Handle error
  //...
});

После

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

Для получения дополнительной информации см. Руководство разработчика AngularJS — миграция с Версии 1.5–1.6

См. также https://stackoverflow.com/a/35331339/5535245

person georgeawg    schedule 20.03.2017

используйте then таким образом, чтобы поймать ответ. обязательно используйте response.data, потому что данные ответа относятся к свойству data

$http.get("http://localhost:8080/chercherProduits?mc")
.then(function(response){
     $scope.pageProduits=response.data;
},function(response){
     console.log(response.data);
}) 

используйте ng repeat для отображения данных по строкам

<body ng-app="MyApp" ng-controller="MyController">
   <div class="container">
      <table class="table table-striped">
         <thead>
            <tr >
               <th>ID</th>
               <th>Désignation</th>
               <th>Prix</th>
               <th>Quantité</‌​th> 
            </tr>
         </thead>
         <tbody>
            <tr ng-repeat="p in pageProduits">
               <td>{{p.id}}</td>
               <td>{{p.designation}}</td>
               <td>{{p.prix}}</td>
               <td>{{p.quantite}}</td>
            </tr>
         </tbody>
      </table>
   </div>
   <script type="text/javascript" src="node_modules/angular/angular.min.js"></script> <script type="text/javascript" src="js/app.js"></script> 
</body>
person Sachila Ranawaka    schedule 20.03.2017
comment
спасибо Сачила var app=angular.module("MyApp",[]); app.controller("MyController",function($scope,$http){ $scope.pageProduits=null; $http.get("http://localhost:8080/chercherProduits?mc") .then(function(resonse){ $scope.pageProduits=resonse.data; },function(resonse){ console.log(resonse.data); }) }); - person Rania El'Oueslati; 20.03.2017
comment
.......... ‹/head› ‹body ng-app=MyApp ng-controller=MyController› ‹div class=container› ‹table class=table table-striped› ‹thead› ‹tr› ‹th ›ID‹/th›‹th›Обозначение‹/th›‹th›Приз‹/th›‹th›Количество‹/th› ‹/tr› ‹/thead› ‹tbody› ‹tr › ‹td›{{p .id}}‹/td› ‹td›{{p.обозначение}}‹/td› ‹td›{{p.prix}}‹/td› ‹td›{{p.quantite}}‹/td› ‹/tr› ‹/tbody› ‹/table› ‹/div› ‹script type=text/javascript src=node_modules/angular/angular.min.js›‹/script› ‹script type=text/javascript src=js/ app.js›‹/script› ‹/body›‹/html›` - person Rania El'Oueslati; 20.03.2017
comment
но результат не отображается :( никаких ошибок, как раньше, с js в порядке, но я не вижу строки, как в tertorial .. вы можете мне помочь? - person Rania El'Oueslati; 20.03.2017
comment
yesss sachila ^__^ просто ng-repeat=p в pageProduits.content не только ng-repeat=p в pageProduits. bcz на этой странице (json) есть много информации о продукте страницы totalPages: 24, totalElements: 120, last: false, size: 5, number: 0, sort: null, numberOfElements: 5, first: true .. content это необходимость - person Rania El'Oueslati; 20.03.2017
comment
Без проблем. Не забудьте отметить как ответ, если это помогло - person Sachila Ranawaka; 20.03.2017

Служба AngularJS $http отправляет запрос на сервер и возвращает response. Используйте then вместо success, как показано ниже:

var app=angular.module("MyApp",[]);
app.controller("MyController",function($scope,$http){
$scope.pageProduits=null;

$http.get("http://localhost:8080/chercherProduits?mc")
.then(function(data){  // function that execute on ajax success
     $scope.pageProduits=data.data;
}, function error(function(err){  //function that execute on ajax error
     console.log(err.statusText);
});
});
person Hikmat Sijapati    schedule 20.03.2017

Согласно официальной документации angular Js. Методы Success и error больше не доступны. Эти методы устарели, вместо них рекомендуется использовать стандартный метод .then. Методы Succces возвращают только data из ответа, но в методе .then возвращается полный объект response.

var app=angular.module("MyApp",[])
.controller("MyController",function($scope,$http){
    $scope.pageProduits=null;

    $http.get("http://localhost:8080/chercherProduits?mc")
    .then(function(response){
         if(response.status === 200) {
             $scope.pageProduits=response.data
         }
    }, function(error) {
        console.log(error)
    });
});

Для получения дополнительной информации: https://docs.angularjs.org/api/ng/service/$http

person Arun Redhu    schedule 20.03.2017