为什么我的 Angular 代码没有按顺序打印/运行



试图理解为什么某些代码行先于其他代码行运行,即使它们不是按该顺序编写的。

我在下面的SO文章中看到他们正在建议承诺:

以角度/打字稿执行顺序代码

这里是否推荐这样做,更重要的是,为什么?我不明白那篇文章中的原因;它更关注如何。

我尝试研究js单线程,承诺,可观察量等。我也一直在学习一个教程,它谈到了组件、模块、数据绑定、指令等,但不明白为什么。

ngOnInit() {
  this.printNames(); //Gets info from database and creates a reactive form , then prints values to console      
  console.log("NgOnInit AFTER printNames()..");
}
printNames() {
this.GetUserInfoFromDB(userID.subscribe(result => {
    this.dbt = result;
    this.createForm();
}

createForm() {
  this.profileForm = this.formbuilder.group({
    'firstName': [this.dbt.firstName],
    'lastName': [this.dbt.lastName],
  });
  console.log(this.profileForm.controls["firstName"].value);
  console.log(this.profileForm.controls["lastName"].value);
}

-

GetUserInfoFromDB(userID: string) Observable<AProfile> {
    let url = URL + '/GetUserInfo';
    let Params = new HttpParams();
    Params = Params.append('userID' userId);
    return this.http.get<AProfile>(url, {params: Params}).pipe( 
      catchError(this.handleError);
}

(实际结果(控制台显示:

  • "NgOnInit AFTER printNames((..">

  • "约翰">

  • "史密斯">

(期望(但我希望名字先打印,然后打印"NgOnInit AFTER"

this.http.get 是一个异步调用。HTTP 请求在您的第一个日志之前发送,然后 printNames 方法完成,因此您拥有第一个日志,然后您收到 http 响应,以便执行订阅方法中的代码(包括具有 2 个日志的 createForm 方法(。

最新更新