试图理解为什么某些代码行在其他代码行之前运行,即使它们未按该顺序编写。
我在下面的SO文章中看到他们在暗示承诺:
Sequential code execution in angular/ typescript
这是这里推荐的,更重要的是,为什么?我不理解那篇文章中的“为什么”。它的重点更多,如何。
我尝试研究js单线程,promise,observables等。我也一直在学习一个教程,该教程讨论了组件,模块,数据绑定,指令等,但不理解为什么。
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);
}
(实际结果)控制台显示:
“在printNames()之后执行NgOnInit。”
“约翰”
“史密斯”
(期望)但我希望先打印该名称,然后再打印“ NgOnInit之后”
答案 0 :(得分:2)
this.http.get是一个异步调用。 在第一个日志之前发送了http请求,然后printNames方法完成,因此您拥有了第一个日志,然后收到了http响应,因此执行了subscription方法中的代码(包括带有2个日志的createForm方法)。