【发布时间】:2020-08-12 15:53:34
【问题描述】:
我有一项服务,可以将来自后端的用户信息存储在本地存储中。我希望存储调用完成,然后继续执行代码,因为我需要立即从本地存储访问数据。
我的服务代码:
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();
}
}
【问题讨论】:
-
当前状态的错误或问题是什么?
标签: javascript angular asynchronous