angular - 使 Angular 函数等待订阅完成
问题描述
我有一个 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
}
推荐阅读
- python - Python 不能在列表推导中使用三元运算符解包
- python - 比较数据集中的当前行和上一行
- string - PANDAS str.contains 令牌匹配排序问题
- php - php中的下一行函数
- javascript - C3.js 堆叠条形图,每个类别有重叠
- visual-studio - 一段时间不活动后与 Mac 的连接丢失
- laravel - 无法使用 laravel 5.5 将 .env 变量设置到我的视图/js 文件中
- android - 在 Android 上未收到通知
- javafx - 在运行时 JavaFx 上设置 TextField 提示文本
- ejabberd - Ejabberd 17.12 内存泄漏