Angular http 在第一次请求时不返回值
Angular http not rerurn value on first request
当第一次调用这个函数时,它 return 没什么,但是当我再次尝试时它 return 真实数据。
我不知道为什么,
我的考试:
getUserAccountInfo(token: string | null): Observable<UserAccount> {
return this.http.get<UserAccount>(
AUTH_API + '/get_user_account_info?token=' + token
);
}
public getCurrentUserAccount(): any {
let token = this.getToken();
let check = new UserAccount();
this.authService.getUserAccountInfo(token).subscribe({
next: (data) => (this.currentUserAccount = data),
error: (err) => console.log(err),
});
return this.currentUserAccount;
}
问题是您在订阅完成之前返回。你需要以某种方式等待它。在下面的示例中,我使用承诺等待它:
export class MyService {
async getCurrentUserAccount(): any {
let token = this.getToken();
let check = new UserAccount();
this.currentUserAccount = await this.authService
.getUserAccountInfo(token)
.pipe(first()) // Import first() from rxjs
.toPromise();
return this.currentUserAccount;
}
}
export class App {
async ngOnInit() {
const userAccount = await this.myService.getCurrentUserAccount();
}
}
当第一次调用这个函数时,它 return 没什么,但是当我再次尝试时它 return 真实数据。 我不知道为什么, 我的考试:
getUserAccountInfo(token: string | null): Observable<UserAccount> {
return this.http.get<UserAccount>(
AUTH_API + '/get_user_account_info?token=' + token
);
}
public getCurrentUserAccount(): any {
let token = this.getToken();
let check = new UserAccount();
this.authService.getUserAccountInfo(token).subscribe({
next: (data) => (this.currentUserAccount = data),
error: (err) => console.log(err),
});
return this.currentUserAccount;
}
问题是您在订阅完成之前返回。你需要以某种方式等待它。在下面的示例中,我使用承诺等待它:
export class MyService {
async getCurrentUserAccount(): any {
let token = this.getToken();
let check = new UserAccount();
this.currentUserAccount = await this.authService
.getUserAccountInfo(token)
.pipe(first()) // Import first() from rxjs
.toPromise();
return this.currentUserAccount;
}
}
export class App {
async ngOnInit() {
const userAccount = await this.myService.getCurrentUserAccount();
}
}