AngularJS 休息 GET 请求不工作

AngularJS Rest GET request not working

我正在开发我的前端(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)
}

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

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

问题是变量 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)
    }
});

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

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

您也可以这样做:

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

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

您需要将所有代码移至 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)
    };

});