簡體   English   中英

制作一個Angular函數等待訂閱完成

[英]Make an Angular function wait for the subscribe to finish

我有一個Angular函數,我試圖通過將其憑據與數據庫進行比較來測試用戶是否有效:

isLoggedIn() {
    this.userService.getUser(this.user.userName)
        .pipe(first())
        .subscribe(
            result => {
                this.currentUser = result;
                if (this.currentUser.fullName != result.fullName) {
                    return false
                }
                return true;
            },
            () => { });

    console.log('The function shouldn't go here')      
}

如何使函數等待我的訂閱完成? 現在,它直接進入console.log行並返回false,然后從api調用中獲取結果

您可以將對userService的訂閱放入構造函數中,然后在成功返回時將值傳遞給“已登錄”函數:

constructor() {
    this.userService.getUser(this.user.userName).subscribe(result => {
        // Could put if statement here to test whether result undefined / valid
        isLoggedIn(result);
    });
};

isLoggedIn(userStatus) {
    // Test and take action with userStatus value
}

暫無
暫無

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

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