【问题标题】:Angular async await in service not working服务中的角度异步等待不起作用
【发布时间】: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


【解决方案1】:

Jason 是对的,你可以像这样声明 ngOnInit:

 async ngOnInit() {
    console.log(JSON.stringify(this.authService.getAccount()));
    await this.setAccount();
    console.log("HomeLayout " + this.globals.AccountId);
  }

【讨论】:

    【解决方案2】:

    this.setAccount() 返回一个你没有等待的承诺。由于 ngOnInit() 不是异步函数,你需要使用 .then()

    【讨论】:

      猜你喜欢
      • 2018-07-08
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 2018-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多