簡體   English   中英

AngularJS解決$ http承諾太晚了

[英]AngularJS resolving $http promise too late

我已經編寫了一個AngularJS工廠profileService ,用於處理設置/獲取用戶配置文件信息。 它的getProfile方法調用了我的Web API,返回了一個包含用戶數據的JSON對象,並使用該數據解析了$http.get承諾。 在身份驗證工廠成員的login方法中使用了此特定的Promise。 login中的代碼塊處於返回其自己的$http.post承諾(正在請求令牌)的過程中。 這個想法是在登錄時檢索並在本地緩存用戶的個人資料數據。

問題是$http.get承諾解決得太遲了。 也就是說,在我的控制台輸出中,調用顯示為未解決( undefined ),緊隨其后的是getProfile的內聯輸出,顯示成功檢索了配置文件對象。 調用存儲了已解決的Promise的變量也會產生undefined

根據我的研究,我傾向於這個問題,因為我沒有正確考慮承諾。 非常感謝您了解我在哪里出錯了!

代碼:profileService.getProfile(userName):

profileService.getProfile = function(userName) {
    return $http.get(ntSettings.apiServiceBaseUri + '/api/Profile/GetProfile?userName=' + userName)
        .then(function(response) {
            return response.data;
        });
};

代碼:authService.login()調用getProfile

var profileService = $injector.get('profileService');
var userProfile = {};

profileService.getProfile(loginData.userName)
    .then(function(response) {
        userProfile = response;
        console.debug("authSvc -> login -> getProfile: Got profile data:", response.userProfile);
    }, function(error) {
        console.error("authSvc -> login: Unable to fetch profile", error);
    });
console.debug("authSvc -> login: Displaying profile object", response.userProfile);

控制台調試輸出顯示問題

authSvc -> login: Showing profile object: undefined
authSvc -> login -> getProfile: Got profile data: Object {FirstName: "John", LastName: "Doe", Birthday: "2015-05-06T04:00:00", Gender: 0, Location: "New York, NY"}

您需要將處理結果的邏輯放在.then()塊中,“顯示配置文件對象”日志記錄不在應用程序的http-request-response部分之外。 您可以將其視為獨立運行的不同執行線程,並且不能假設“ before”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM