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

问题描述:

嗨,我试图得到一个http请求的状态并有条件地设置一个变量。我正在做一个subcall来检查user1是否跟随user2。我的代码看起来像这样。 (为简便起见我剪的是通过我以前得到要求我之所以要推的用户的列表需要循环在foreach功能)if语句来检查http请求的状态AngularJS

$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

+0

你问如何编写'GetUserFollowers'函数,以便返回这些状态码?如果这是您正在尝试编制逻辑的功能,那么现在查看您的代码会很有帮助...... – Claies

+0

@Claies检查编辑..由于某种原因编辑后的代码将其设置为true或假错误 – teddybear123

+0

什么,就像'$ http'调用的状态返回的东西不是'HTTP 200'和'$ scope.data.is_following'仍然以某种方式结束了吗? – Claies

$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块。

+0

问题在于我设置的变量没有被推送.. – teddybear123

+0

'.success'和'.error'已被弃用,并且在Angular 1.6中不再可用。 –