When first call this function, it return no thing but when i try again it return true data. idk why, My Exam:
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;
}
CodePudding user response:
public getCurrentUserAccount(): any {
let token = this.getToken();
let check = new UserAccount();
this.authService.getUserAccountInfo(token).subscribe({
next: (data) => (this.currentUserAccount = data;
return this.currentUserAccount;),
error: (err) => console.log(err),
});
you can try this change
}
CodePudding user response:
The problem is that you are returning before the subscription finishes. You need to wait for it somehow. In the example below I wait for it using a promise:
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();
}
}