简体   繁体   English

if语句检查获取请求AngularJS的http状态

[英]if statement to check http status of get request AngularJS

Hi i'm trying to get the status of an http request and conditionally set a variable. 嗨,我正在尝试获取http请求的状态并有条件地设置变量。 I'm making a subcall to check if user1 is following user2. 我正在制作一个子网来检查user1是否跟随user2。 My code looks like this. 我的代码看起来像这样。 (for brevity i cut the foreach function that needs to loop through a list of users that i have previously get requested reason why i have to push) (为了简洁起见,我切断了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);         
        });

    };

Tried this didn't work 试过这个没用

$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 is my service: 这是我的服务:

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

!NOTE - begin and End are ignored if to_id is not -1 !注意 - 如果to_id不是-1,则忽略begin和End

$http returns status code as the second argument. $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); 
  });

However, if the status is an error status, such as 404, then the error block will be called. 但是,如果状态是错误状态,例如404,则将调用error块。

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

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