生命周期事件中的Angular HTTP同步请求

问题描述 投票:0回答:1

在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);
  }
}
angular rxjs observable angular-httpclient rxjs6
1个回答
0
投票

我唯一能想到的是使用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

© www.soinside.com 2019 - 2024. All rights reserved.