【问题标题】:Assign value to the variable based on returning data from the subscribe in Angular . (Is it possible ?)根据从 Angular 中的订阅返回的数据为变量赋值。 (可能吗 ?)
【发布时间】:2021-10-18 04:56:09
【问题描述】:
somefunction(){
    isUserLoggedin(): boolean {
        this.isUserInDB().subscribe((result: any) => {
          if (result.code === 200) {
            return true;
          }
        });
      return false;
  }

isUserInDB():此 API 从本地存储中获取令牌,如果用户存在于 DB 中,则返回 200;如果用户不存在于 DB 中,则返回 404(有人试图尝试他/她自己的令牌。)

在这种情况下,我总是得到 false 我知道,因为首先执行 return false,然后调用 subscribe 方法。所以我想知道是否存在任何其他方式或者我只是在做一些额外的事情?

【问题讨论】:

  • 订阅是异步的。应用程序不知道 observable 何时会发出它的值。所以没有办法从订阅中同步返回值。换句话说,您需要在需要响应的地方订阅。
  • isUserLoggedin 缺少 .pipe(first()) 因此订阅会在每次调用时自行销毁,否则如果您第二次调用 isUserLoggedin,订阅将触发 2 次,依此类推。您正在累积订阅

标签: angular typescript promise rxjs-observables


【解决方案1】:

由于this.isUserInDB() 是异步的,isUserLoggedin 将始终返回 false。你可以做的是返回 observable 而不是 boolean 并在你调用这个函数的地方处理这个:

isUserLoggedin(): Observable<any> { // replace any with your type
    return this.isUserInDB();
}

如果您想根据用户登录执行一些逻辑,您可以订阅此功能并执行您的任务:

isUserLoggedIn.subscribe((result: any) => {
          if (result.code === 200) {
             // Your code
          }

理想情况下,在您的登录流程中,您应该将用户的登录状态存储在某些服务中并返回。

【讨论】:

    【解决方案2】:

    定义一个类的属性并将其初始化为false:

    isUserInDb = false
    

    创建组件时,如果结果状态为成功,则将属性更改为true:

    ngOnInit() {
        this.isUserInDB().subscribe((result: any) => {
            if (result.code === 200) {
                this.isUserInDb = true;
            }
        });
    }
    

    【讨论】:

      【解决方案3】:

      我对此的看法是通过 async/await 同步它

      async isUserLoggedin(): Promise<boolean> {
         const result = await this.isUserInDB().pipe(first()).toPromise();
      
         if (result.code === 200) {
            return true;
         } else {
            return false;
         }
      }
      

      用法:

      async somefunction(): Promise<void> {
          const logged = await this.isUserLoggedin();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-07-20
        • 1970-01-01
        • 2017-02-23
        • 2019-05-27
        • 1970-01-01
        • 1970-01-01
        • 2020-02-18
        相关资源
        最近更新 更多