AngularJS Promise 的 success 函数

3

我已经向一个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个回答

3

Angular在$http实现中使用promise(承诺)机制, 即$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.error已经被弃用了。

因此,请选择第二个选项。

第二个选项

使用.then函数替代

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

}

$http(req).then(function() {
    // do on response success
}, function() {
   // do on response failure
});

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

这是成功和错误语法

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

使用 then

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

1

$http 返回一个 Promise,其中包含您可以使用的 then 函数。

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

then的定义:

then(successCallback, failCallback)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接