Angular 如何从RXJS的角度可观测函数处理返回值
我在Angular中有一个登录视图。我已提出:Angular 如何从RXJS的角度可观测函数处理返回值,angular,typescript,rxjs,angular-observable,Angular,Typescript,Rxjs,Angular Observable,我在Angular中有一个登录视图。我已提出: 用于获取用户数据的用户服务 用于检查有效用户的身份验证服务 因此,从登录视图,我将用户名传递给AuthService,它与UserService联系以获取数据,并处理数据,返回一个布尔值,无论用户是否有效 登录视图中的代码如下所示: 认证服务: this.authenticationService.checkValidLogin(用户名、密码); 认证服务: checkValidLogin(用户名:string,密码:string){ thi
布尔值,无论用户是否有效
登录视图中的代码如下所示:
认证服务:
this.authenticationService.checkValidLogin(用户名、密码);
认证服务:
checkValidLogin(用户名:string,密码:string){
this.userService.getUserByEmail(username.snapshotChanges().pipe(map(data=>data.map(c=>({key:c.payload.doc.id,…c.payload.doc.data())))。订阅(res=>{
if(res[0]。密码===密码){
返回true;
}否则{
返回false;
}
});
}
我有返回true
或false
的命令,但这不会返回到方法
我想从订阅中返回true
或false
值,或者我在这里缺少了什么?由于代码是异步的,所以您必须返回可观察的
,并在检查其有效性时订阅它
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.userService.getUserByEmail
之前添加return,如下所示
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;
}
});
我还建议只返回res[0]。password===password
,因为它返回一个布尔值您从userService接收的数据是数组吗?我这样问是因为您调用了它的map操作data.map(c=>({key:c.payload.doc.id,…c.payload.doc.data()})
我会检查并让您知道..!!感谢您的回答,我会检查并让您知道,因为它更简单的解决方案会批准它,如果它有效..!!这不起作用,在这种情况下,我们将返回订阅的方法和订阅的内部我们将返回true
或false
。
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;
}
});