正如我上面提到的,我使用一个函数向后端发送一个http请求来获取一些数据,这会返回一个可观察到的数据;当我调用该函数时,我必须订阅它以便处理它的返回,然后我在订阅之后执行一些额外的代码,包括一些if语句,我注意到在获取数据之前执行订阅方法下面的代码。我尝试使用异步等待,但它似乎不起作用,直到我使用toPromise()将返回(可观察到)转换为承诺;然后它工作得很好;我的问题是,在订阅()完成之前,是否有任何方法使下面的代码订阅,使用toPromise()(因为它被废弃了);
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);
}
提前谢谢。
发布于 2022-09-07 16:09:43
对于那些可能存在相同问题的人,我第一次使用toPromise()解决了这个问题,但是由于不推荐使用它,所以我寻找了一个更好的选项,因此我找到了firstValueFrom和lastValueFrom,而且由于我的方法应该返回一个适合我的值,所以我的代码变成了:
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));
}现在我的代码运行得很完美。非常感谢你的回答。
https://stackoverflow.com/questions/73627881
复制相似问题