我有一项将来自后端的用户信息存储在本地存储中的服务。我想完成存储调用,然后继续执行代码,因为我需要立即访问本地存储中的数据。
我的服务代码:
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();
}
}
答案 0 :(得分:0)
this.setAccount()返回您没有等待的承诺。由于ngOnInit()不是异步函数,因此您需要使用.then()
答案 1 :(得分:0)
Jason是正确的方式,您可以这样声明ngOnInit:
async ngOnInit() {
console.log(JSON.stringify(this.authService.getAccount()));
await this.setAccount();
console.log("HomeLayout " + this.globals.AccountId);
}