2013-03-08 35 views
4

我正在嘗試將登錄用戶從登錄頁面重定向到遠離登錄頁面(如果他們嘗試在應用程序中訪問它)。與登錄頁面關聯的控制器 - Login_controller調用授權服務中的功能 - Authorisation_service.isLoggedIn()。如果此服務返回true,則應將用戶重定向到登錄的概述頁面。AngularJS - 控制器不等待條件語句中的服務返回值

通過記錄到控制檯我可以看到,在服務返回true之前,條件語句已經聲明從服務返回的值是未定義的。之後服務確實會恢復正常,但已爲時過晚。

如何讓控制器的條件語句等待服務的返回值?

Authorise_service.js

myApp.factory('Authorise', ['User', '$http', '$location', '$rootScope', function(User, $http, $location, $rootScope) { 
    return { 
     isLoggedIn: function() { 
      if(((sessionStorage.username && sessionStorage.authKey) && (sessionStorage.username !== "null" && sessionStorage.authKey !== "null")) || ((localStorage.username && localStorage.authKey) && (localStorage.username !== "null" && localStorage.authKey !== "null"))) { 
       if(sessionStorage.username) { 
        var usernameLocal = sessionStorage.username; 
        var authKeyLocal = sessionStorage.authKey; 
       } else { 
        var usernameLocal = localStorage.username; 
        var authKeyLocal = localStorage.authKey; 
       } 
       //pass to server 
       var user = User.query({ usernameLocal: usernameLocal, authKeyLocal: authKeyLocal }, function(user) { 
        if(user.loginSuccess === 1) { 
         return true; 
        } else { 
         return false; 
        } 
       }); 
      } else { 
       return false; 
      } 
     } 
    }; 
}]); 

Login_controller.js

myApp.controller('Login_controller', function(Authorise, $scope, $location) { 
    if(Authorise.isLoggedIn() === true) { 
     console.log("Authorise.isLoggedIn() = true"); 
     $location.path('/teach/overview'); 
    } 
}); 

回答

5

Smk是對的。您可能試圖依靠服務器尚未返回的數據。 「然而」是這裏的關鍵問題,因爲很可能您的數據可以從服務器中正確提取,您只需在準備好之前就參考結果!要檢查這是否是事實,只需在User.query(...)回撥中添加console.log(user)即可。

Smk指出你正確的方法 - 使用PROMISE API。基本上,諾言是一個對象,當服務器準備好結果時,您可以進一步使用它來執行一些操作。爲了說明這一點:

function myFunc() { 
    var result = false; 

    // You are calling async request to the server, so the execution won't wait for the 
    // results. It will simply fire server request and proceed to next lines. 
    serverCall(function(srvResponse){ 

     result = srvResponse.everythingIsGood; // This will be called after the whole method finishes! 
    }); 

    return result; // This will MOST PROBABLY return 'false' all the times. 
} 

而且這樣做的正確方法:

function theRealLogicYouWantToDo(result) { 
    if (result) { 
     // ... 
    } else { 
     // ... 
    } 
} 

serverCall(function(srvResponse) { 
    theRealLogicYouWantToDo(srvResposne.everythingIsGood); 
}); 

This is nice tutorial這一切jQuery中。它不僅用於服務器調用,而且還用於JS中的其他地方。很好學習它。

+0

感謝您的詳盡回覆和教程鏈接非常有用 – Fisu 2013-03-08 13:09:31

+0

很高興能幫助您,先生! – 2013-03-10 15:13:37

3

您需要返回promise

您的angularjs服務可以返回一個承諾,您可以在控制器中測試該值。

相關問題