Angular 如何使typescript按顺序执行代码?

Angular 如何使typescript按顺序执行代码?,angular,typescript,Angular,Typescript,我的代码似乎并不等待执行某些代码,而是更进一步 isAdmin(): boolean { this.getLoggedUser(); this.getRole(); console.log(this.admin); console.log('isAdmin'); return this.admin; } getRole() { this.httpClient.get<boolean>('/api/has-role-admin'

我的代码似乎并不等待执行某些代码,而是更进一步

isAdmin(): boolean {
    this.getLoggedUser();
    this.getRole();
    console.log(this.admin);
    console.log('isAdmin');
    return this.admin;
  }

  getRole() {
    this.httpClient.get<boolean>('/api/has-role-admin').
    subscribe((data) => {
    this.admin = data;
    console.log(this.admin);
    console.log('getRole');
    }
    );
 }

我想完成getRole方法,然后在isAdmin中完成其余步骤。我怎样才能接收到这种行为?

您的代码是不连续的,因为您订阅了一个可观察的:

isAdmin(): boolean {
    this.getLoggedUser();
    this.getRole();
    console.log(this.admin);
    console.log('isAdmin');
    return this.admin;
  }

  getRole() {
    this.httpClient.get<boolean>('/api/has-role-admin').
    subscribe((data) => {
    ------------------------------------- This block will complete after the method returns
      this.admin = data;
      console.log(this.admin);
      console.log('getRole');
    }
    );
}
如果您的代码涉及可观察的对象,则根据定义,它不能是连续的。您需要重构您的方法,以便使用可观察的,而不依赖subscribe方法中的副作用

我将以这种方式重构您的代码我对您的代码做了一些假设,但是,总体思路应该是:

public interface UserInfo{
    public isAdmin: boolean = false;
}

public getUserInfo(userId: integer): Observable<UserInfo> {
    let params = new HttpParams()
        .append('userId', userId.toString());

    return this.http.get<UserInfo>(this.baseUrl + "api/has-role-admin", { params: params });
}

public isAdminUser(userId: number): Observable<boolean>(){
    return this.getUserInfo(userId).pipe(map(x=> { return x.isAdmin; }));
}

服务器端api应该返回UserInfo。您可以调用isAdminUserthis.getLoggedUser.userId。

这是在控制器中吗?名为isAdmin的方法可能不应该进行HTTP调用,尤其是当模板调用它时,因为这样您将多次进行HTTP调用

相反,编写一个ngOnInit,在其中进行调用并将结果存储到组件上的实例变量中

此外,HTTP调用需要时间,并且永远不要在Javascript中阻塞线程。因此,HTTP调用生成您订阅的可观察对象。订阅会立即发生,但在HTTP响应到达之前不会执行回调


处理这个问题的两种常见模式是使用ngIf隐藏元素,直到它被加载为止,或者使用异步管道。

不要订阅。类似这样的内容:另外,请记住console.log是异步的。在某些浏览器中。感谢您的建议,这次console.log是正确的:但另一个问题是,当我将isAdmin创建为异步时,如何使它仍然返回布尔值?
public interface UserInfo{
    public isAdmin: boolean = false;
}

public getUserInfo(userId: integer): Observable<UserInfo> {
    let params = new HttpParams()
        .append('userId', userId.toString());

    return this.http.get<UserInfo>(this.baseUrl + "api/has-role-admin", { params: params });
}

public isAdminUser(userId: number): Observable<boolean>(){
    return this.getUserInfo(userId).pipe(map(x=> { return x.isAdmin; }));
}