如何解决角异步等待服务不起作用
我有一项将来自后端的用户信息存储在本地存储中的服务。我想完成存储调用,然后继续执行代码,因为我需要立即访问本地存储中的数据。
我的服务代码:
async setAccount(){
if(this.globals.AccountId==0)
{
console.log("Account Id is 0");
if(localStorage.getItem('AccountDetails')){
console.log("Local Storage is there");
let AccDetails=JSON.parse(localStorage.getItem('AccountDetails'));
this.globals.AccountId=AccDetails["AccountId"];
}
else{
console.log("No local storage found");
let AccountObj = JSON.parse(JSON.stringify(this.authService.getAccount()));
let AzureId: string = AccountObj["accountIdentifier"];
console.log(AzureId);
const sendObj: GetAccountByIdQuery = {
AzureAccountId: AzureId
};
console.log("Sending Backend request");
let res=await this.getAccountById(JSON.stringify(sendObj));
console.log(res);
this.globals.AccountId=res["AccountId"];
console.log(this.globals.AccountId);
localStorage.setItem('AccountDetails',JSON.stringify(res));
}
}
}
async getAccountById(sendObject: string) { // : Observable<string> {
console.log("Backend request");
return await this.http.post<string>(this.AccountUrl + 'GetAccountById',sendObject,this.httpOptions)
.pipe(
retry(3) // retry a failed request up to 3 times
).toPromise();
}
我正在访问如下方法:
@Component({
selector: 'app-home-layout',templateUrl: './home-layout.component.html',styleUrls: ['./home-layout.component.css']
})
export class HomeLayoutComponent implements OnInit {
constructor(private authService: MsalService,private accountService: AzureAccountService,private globals: Globals) { }
ngOnInit(): void {
console.log(JSON.stringify(this.authService.getAccount()));
this.setAccount();
console.log("HomeLayout " + this.globals.AccountId);
}
async setAccount() {
await this.accountService.setAccount();
}
}
解决方法
this.setAccount()返回您没有等待的承诺。由于ngOnInit()不是异步函数,因此您需要使用.then()
,Jason是正确的方式,您可以这样声明ngOnInit:
async ngOnInit() {
console.log(JSON.stringify(this.authService.getAccount()));
await this.setAccount();
console.log("HomeLayout " + this.globals.AccountId);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。