AngularJS承诺的成功功能

时间:2016-04-15 07:24:31

标签: angularjs angular-promise angular-http

我已经对URL进行了HTTP post API调用。

我得到了回复,但我很困惑如何编写成功函数,因为它有很多种方法。

这是我的API调用。请帮助我,成功函数将如何?<

var req = {
    method: 'POST',
    url: viewProfileurl,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer ' + $rootScope.token,
    },
    params: {
        'action':'view'
    }
}

$http(req);

4 个答案:

答案 0 :(得分:2)

Angular在$http实施中内部使用承诺,即$q

  

一种帮助您异步运行函数并使用它们的服务   完成处理后返回值(或例外)。

所以,有两种选择:

第一个选项

您可以使用.success.error回调:

var req = {
  method: 'POST',
  url: viewProfileurl,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': 'Bearer ' + $rootScope.token,
  },
  params: {
    'action': 'view'
  }

}

$http(req).success(function() {
    // do on response success
}).error(function() {
});

但是.success&amp; {/ 1}}已被弃用。

所以,请选择第二个选项。

第二选项

使用.error功能

.then

答案 1 :(得分:2)

您需要编写成功回调以检索API返回的数据。

$http(req)
     .then(function (response) {
         var data = resposne.data;
         ...
      }, function (error) {
         var errorStatusCode = error.StatusCode;
         var errorStatus = error.Status;
         ...
      });

基本上$ http会返回一个promise,你需要编写一个回调函数。

或者你可以这样做:

$http(req).success(function(respData) { var data = respData; ... });
$http(req).error(function(err) { ... });

答案 2 :(得分:2)

成功与错误语法

    $http.get("/api/my/name")
  .success(function(name) {
    console.log("Your name is: " + name);
  })
  .error(function(response, status) {
    console.log("The request failed with response " + response + " and status code " + status);
  };

使用然后

$http.get("/api/my/name")
  .then(function(response) {
    console.log("Your name is: " + response.data);
  }, function(result) {
    console.log("The request failed: " + result);
  };

答案 3 :(得分:1)

$http会返回一个可以使用then函数的承诺。

$http(req).then(function (data) { ...; });

then的定义:

then(successCallback, failCallback)