【问题标题】:AngularJS Rest GET request not workingAngularJS Rest GET 请求不起作用
【发布时间】:2016-02-12 18:43:12
【问题描述】:

我正在处理我的前端(Angular Js 调用 Rest 服务),这工作正常,我得到一个很好的 JSON 作为响应:

$scope.test = function(response) {  
    $http.get("http://localhost:8080/androbridge/test/dotest"+"?s=ssss").success(function(response){
    $scope.related=JSON.stringify(response);
}); 

虽然这不起作用:

var x;      
    $http.get("http://localhost:8080/androbridge/einloggen/loggeEin?username=" + $scope.username + "&password=" + $scope.password).success(function(response)
            {x=JSON.stringify(response);})  

    if(x=={"Kennzeichnung":"login","Status":true}){
        $rootScope.loggedIn=true;
        $location.path('/userPage');    
}else {
    alert('Wrong Login Information'+$scope.username +$scope.password + x)
}

有人看到我犯了什么错误吗?我想不通!

【问题讨论】:

  • 你在控制台看到什么错误??

标签: javascript angularjs rest parameter-passing


【解决方案1】:

首先,你不能像这样进行对象比较:

if(x=={"Kennzeichnung":"login","Status":true}){

你可以这样做:

if(x.Kennzeichnung == 'login' && x.Status){

$http.success() 方法也已弃用。你应该改用$http().then(successFn, errorFn);。

【讨论】:

    【解决方案2】:

    问题在于变量 x 在 $http 范围内,而您在外部对其进行测试。 http 调用是异步的。试试这个:

    var x;
    $http.get("http://localhost:8080/androbridge/einloggen/loggeEin?username=" + $scope.username + "&password=" + $scope.password).success(function(response) {
        x = JSON.stringify(response);
        if (x == {
                "Kennzeichnung": "login",
                "Status": true
            }) {
            $rootScope.loggedIn = true;
            $location.path('/userPage');
        } else {
            alert('Wrong Login Information' + $scope.username + $scope.password + x)
        }
    });
    

    【讨论】:

    • 谢谢先生!像魅力一样工作。
    【解决方案3】:

    首先,$http 是异步的,所以你的 if 将在收到响应之前执行。接下来是你的 if 语句,它在语法上不正确。

    【讨论】:

      【解决方案4】:

      您需要将所有代码移动到 Promise 的回调中。承诺回调是异步的,只有在响应从服务器返回时才会被调用。您的代码块当前在回调之外,将立即执行,而不是在返回结果时执行。

      试试这样的

          $http.get("http://localhost:8080/androbridge/einloggen/loggeEin?username=" + $scope.username + "&password=" + $scope.password)
      .success(function(response)
                  {
      
          var x = JSON.stringify(response);
          if(x == {"Kennzeichnung":"login","Status":true}){
              $rootScope.loggedIn=true;
              $location.path('/userPage');    
           }else {
            alert('Wrong Login Information'+$scope.username +$scope.password + x)
          };
      
      });  
      

      【讨论】:

        猜你喜欢
        • 2017-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-04
        • 1970-01-01
        • 1970-01-01
        • 2016-07-27
        • 2014-02-09
        相关资源
        最近更新 更多