Angular HTTP-синхронизация c запрос в событии жизненного цикла - PullRequest
0 голосов
/ 06 мая 2020

В Angular2 +, как убедиться, что HTTP-запрос (или Observable) завершается sh перед go следующей строкой. 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);
  }
}

1 Ответ

0 голосов
/ 06 мая 2020

Единственное, что я могу придумать, - это использовать 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 ));
  }

Я считаю это исправление хакерским приемом, где правильным подходом было бы реагировать на это. Трудно дать вам руководство по реактивному подходу, не имея более широкой картины.

-Isaa c

...