在Angular2+中,如何确保一个HTTP请求(或Observable)在进入下一行之前完成。https:/stackblitz.comeditangular-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);
}
}
我唯一能想到的是使用BehaviorSubject或者只使用Subject。 考虑做如下修改。
systemPreference = new BehaviorSubject<any>({});
ngOnInit(){
console.log("ngOnInit");
//get system preference
this.http.get("https://data.hawaii.gov/api/views/usep-nua7/rows.json").subscribe(res=>{
systemPreference.next(res);
})
ngAfterViewInit(){
console.log("ngAfterViewInit");
systemPreference.subscribe(pref =>
console.log(pref ));
}
我认为这个修复是一个黑客,正确的方法是反应性地处理这个问题。 在没有大局观的情况下,很难给你指导反应式的方法。
-Isaac