【问题标题】:How to return value from function processing observable of RXJS in Angular如何从Angular中RXJS的可观察函数处理返回值
【发布时间】:2020-10-07 15:14:15
【问题描述】:

我在 Angular 中有一个登录视图。我做了:

  1. 一个 UserService 来获取用户数据。

  2. 一个 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;
        }
    });
}

我已经返回 truefalse 但不会返回到方法..!!

我想从订阅中返回 truefalse 值,或者我在这里缺少什么?

【问题讨论】:

  • 从 userService 收到的数据是数组吗?我在问,因为您已经对其调用了地图操作data.map(c => ({ key: c.payload.doc.id, ...c.payload.doc.data() })

标签: angular typescript rxjs angular-observable


【解决方案1】:

由于代码是异步的,所以你需要返回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
});

【讨论】:

  • 我会检查并告诉你..!!
【解决方案2】:

请在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;
  }
});

我也建议只使用return res[0].password === password,因为它返回一个布尔值

【讨论】:

  • 感谢您的回答,我们会检查并通知您,因为如果可行,其更简单的解决方案将批准此操作..!!
  • 这行不通,在这种情况下,我们为方法返回一个Subscription,在Subscription 内部,我们返回truefalse
猜你喜欢
  • 1970-01-01
  • 2020-06-24
  • 1970-01-01
  • 1970-01-01
  • 2021-09-03
  • 2017-06-11
  • 2021-03-25
  • 2021-06-06
  • 2018-04-11
相关资源
最近更新 更多