首页 > 解决方案 > Angular 在服务器响应之前停止程序的执行

问题描述

问题:有一个可以为空的布尔属性isAuthorized,在服务构造函数中向服务器发送请求以获取有关用户的信息并确保他被授权。

private _isAuthorized: boolean | null = null;
public get isAuthorized() {
    return this._isAuthorized;
}
constructor(private http: HttpClient) {
     this.update();
}
async update() {
     try {
         this.data = await this.getUserInfo();
         console.log(this.data.userName);
         this.userName = this.data.userName;
         this._isAuthorized = true;
     }
     catch (err) {
         ...
     }
}
getUserInfo(){
    ...
    return this.http.get<User>(this.url, { headers: header }).toPromise();
}

但是,可以在 isAuthorized 属性仍然为空时访问它(即,直到服务器响应为止)。

标签: angulartypescript

解决方案


推荐阅读