首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >让执行等待订阅()主体,Angular14

让执行等待订阅()主体,Angular14
EN

Stack Overflow用户
提问于 2022-09-06 21:22:36
回答 1查看 68关注 0票数 -1

正如我上面提到的,我使用一个函数向后端发送一个http请求来获取一些数据,这会返回一个可观察到的数据;当我调用该函数时,我必须订阅它以便处理它的返回,然后我在订阅之后执行一些额外的代码,包括一些if语句,我注意到在获取数据之前执行订阅方法下面的代码。我尝试使用异步等待,但它似乎不起作用,直到我使用toPromise()将返回(可观察到)转换为承诺;然后它工作得很好;我的问题是,在订阅()完成之前,是否有任何方法使下面的代码订阅,使用toPromise()(因为它被废弃了);

代码语言:javascript
复制
 public login(
    usernameOrEmail: string,
    password: string
  ): Observable<AppUser> {
    /*
      -tried getting data directly from the backend instead of fetching everything onInit(which i think is not a good idea)
      but that dosn't seem to work since return of http request is an observable, and takes a bit more of time,
      and since i need to do more tests on the data returned (as you see below), the code keeps executing 
      without having the data yet.
     
    */
  this.userService.getUserByUsername(usernameOrEmail).subscribe({
      next: (response: AppUser) => {
        this.authenticatedUser = response;
      },
      error: (error: Error) => {
        throwError(() =>error);
      }
    });

    if (this.authenticatedUser == undefined) {
      return throwError(() => new Error('User not found'));
    }
    if (this.authenticatedUser.password != password) {
      return throwError(() => new Error('Bad credentials'));
    }
    return of(this.authenticatedUser);
  }

提前谢谢。

EN

回答 1

Stack Overflow用户

发布于 2022-09-07 16:09:43

对于那些可能存在相同问题的人,我第一次使用toPromise()解决了这个问题,但是由于不推荐使用它,所以我寻找了一个更好的选项,因此我找到了firstValueFromlastValueFrom,而且由于我的方法应该返回一个适合我的值,所以我的代码变成了:

代码语言:javascript
复制
  public async login(
    usernameOrEmail: string,
    password: string
  ): Promise<Observable<AppUser>> {
    try {
      let response = await this.userService.getUserByUsername(usernameOrEmail);
      this.authenticatedUser = await firstValueFrom(response);
    } catch (error) {
      this.errorMessage = error;
    }
    if (this.authenticatedUser == undefined) {
      return throwError(() => new Error('User not found'));
    }
    if (this.authenticatedUser.password != password) {
      return throwError(() => new Error('Bad credentials'));
    }
    return Promise.resolve(of(this.authenticatedUser));
  }

现在我的代码运行得很完美。非常感谢你的回答。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73627881

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档