[英]How to return value from function processing observable of RXJS in Angular
我在 Angular 有一個登錄視圖。我做了:
用於獲取用戶數據的UserService 。
用於檢查有效用戶的AuthService 。
因此,從登錄視圖,我將用戶名傳遞給AuthService ,它與UserService聯系以獲取數據並操作數據並返回boolean
值,無論用戶是否有效。
登錄視圖下方的代碼如下:
認證服務:
this.authenticationService.checkValidLogin(userName,password);
認證服務:
checkValidLogin(username: string, password: string) {
this.userService.getUserByEmail(username).snapshotChanges().pipe(map(data => data.map(c => ({ key: c.payload.doc.id, ...c.payload.doc.data() })))).subscribe(res => {
if (res[0].password === password) {
return true;
} else {
return false;
}
});
}
我已經返回true
或false
但不會返回到方法..!!
我想從訂閱中返回true
或false
值,或者我在這里缺少什么?
由於代碼是異步的,當你想檢查它的有效性時,你必須返回Observable
並訂閱它。
checkValidLogin(username: string, password: string): Observable<boolean> {
return this.userService.getUserByEmail(username).snapshotChanges().pipe(map(data => data.map(c => ({ key: c.payload.doc.id, ...c.payload.doc.data() }))),
// map result to true or false
map(res => {
if (res[0].password === password) {
return true;
} else {
return false;
}
})
);
然后當你想使用它時:
this.authenticationService.checkValidLogin(userName,password).subscribe(valid => {
console.log(valid); // do your logic here of everything that determines if it's valid or not
});
請在this.userService.getUserByEmail
之前添加回車,如下所示。
checkValidLogin(username: string, password: string){
return this.userService.getUserByEmail(username).snapshotChanges().pipe(map(data => data.map(c => ({ key: c.payload.doc.id, ...c.payload.doc.data() })))).subscribe(res => {
if (res[0].password === password) {
return true;
} else {
return false;
}
});
我還建議只return res[0].password === password
因為它返回 boolean 值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.