gpt4 book ai didi

javascript - if 语句检查 get 请求 AngularJS 的 http 状态

转载 作者:行者123 更新时间:2023-11-30 12:20:11 25 4
gpt4 key购买 nike

您好,我正在尝试获取 http 请求的状态并有条件地设置一个变量。我正在进行子调用以检查 user1 是否在关注 user2。我的代码看起来像这样。 (为简洁起见,我删除了需要循环遍历用户列表的 foreach 函数,我之前收到请求的原因是我必须推送)

$scope.users = [];
var getUser = function(id) {
UserService.GetUserById(id, $localStorage.CurrentUser.auth_token)
.success(function (data) {

data = angular.fromJson(data);

//data model ==> {id: 0, username: "foo"}

//check if 404 or 200 ==> UserService.GetUserFollowers($stateParams.id, data.id)
//if 200 data.is_following = 1; if 404 data.is_following = 0

$scope.users.push(data);

//data model after pushed ==> {id: 0, username: "foo", is_following: 1}

console.log(angular.toJson($scope.users));

}).error(function(error, status) {
alert(status);
console.log(error);
});

};

试过了没用

$scope.users = [];
var getUser = function(id) {
UserService.GetUserById(id, $localStorage.CurrentUser.auth_token)
.success(function (data) {

$scope.data = angular.fromJson(data);

UserService.GetUserFollowers($stateParams.id, $scope.data.id, -1, -1)
.success(function(data, status) {
$scope.status = status;
}).error(function(data, status) {
$scope.status = status;
});

if ($scope.status === 200) {
$scope.data.is_following = true;
}else{
$scope.data.is_following = false;
}

$scope.users.push($scope.data);

console.log(angular.toJson($scope.users));

}).error(function(error, status) {
alert(status);
console.log(error);
});

};

这是我的服务:

  this.GetUserFollowers = function (my_id, to_id, begin, end) {
return $http.get($rootScope.endPoint + '/user/' + my_id + '/followers/' + to_id + '/' + begin + '/' + end + '/');
};

!注意 - 如果 to_id 不是 -1,begin 和 End 将被忽略

最佳答案

$http 返回状态代码作为第二个参数。

$http.get(url)
.success(function(data, status) {
alert(status); // HTTP status code of the response
})
.error(function(data, status) {
alert('Error with status code: ' + status);
});

但是,如果状态是错误状态,例如 404,则将调用 error block 。

关于javascript - if 语句检查 get 请求 AngularJS 的 http 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31373851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com