【发布时间】:2020-05-06 02:59:28
【问题描述】:
在 Angular2+ 中,如何确保 HTTP 请求(或 Observable)在进入下一行之前完成。 https://stackblitz.com/edit/angular-uvtfln
export class AppComponent implements OnInit, AfterViewInit {
name = 'AngularX';
systemPreference: any;
constructor(private http: HttpClient){
}
ngOnInit(){
console.log("ngOnInit");
//get system preference, it is used in whole app,
//it needs to be available so other component can use it.
this.http.get("https://data.hawaii.gov/api/views/usep-nua7/rows.json").subscribe(res=>{
//How to make it is done before go to the next life circle event?
this.systemPreference = res;
})
}
ngAfterViewInit(){
console.log("ngAfterViewInit");
//the below got undefined, I expect the subscriber must be done at ngOnInit
//before reaching this function (ngAfterViewInit)
console.log(this.systemPreference);
}
}
【问题讨论】:
-
由于您没有从该方法返回任何内容,因此它无法等待,但无论如何,angular 无论如何都不支持这一点。你需要调整你的代码。为什么你需要在一个钩子中执行部分逻辑而在另一个钩子中执行部分逻辑?有一些框架,比如 Aurelia,支持异步生命周期钩子,但 Angular 不是其中之一。但是,即使是这样,这也不是该支持的好用例。请解释为什么要在不同的生命周期钩子中执行部分逻辑
-
想象它是系统信息并且在整个应用程序中使用,它需要可用,以便其他组件可以使用它。
-
这与生命周期挂钩没有任何关系
标签: angular rxjs observable angular-httpclient rxjs6