Синхронный вызов функций в ngOnInit - PullRequest
0 голосов
/ 18 мая 2018

Я работаю над Angular 4, и у меня сразу много разных функций, запущенных в ngOnInit ().Большинство из них - это http-запросы с обратными вызовами, которые обрабатывают данные и передают их следующей функции.

В настоящее время я использую setTimeouts, чтобы убедиться, что все идет в правильном порядке.Однако, это не всегда идет хорошо, например, с более медленными интернет-соединениями.Я хотел бы убедиться, что все идет в правильном порядке без таймаутов. Для этого я рассмотрел обещания и асинхронное ожидание, но мне не удается реализовать его в моем приложении, поскольку функции, вызываемые в onInit, выполняют гораздо больше, чем просто вызовы http.Я не уверен, куда мне поместить код из текущих обратных вызовов.

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

ngOnInit() {

this.getPolygons();

this.customerMasterData();
this.loadMap();

setTimeout(() => this.ngOnInitAfterTimeout(), 2000);}



getPolygons() {
this.dataService.portfolioPolygon()
  .subscribe(
    (response: Response) => {
      const data = response.json();
      const polygon = data.polygons;
      if (polygon) {
        polygon.forEach((item, index) => {
          this.polygons.push(item.polygon);
          this.polygonId.push(item.identificatie);
        });
      }
    },
    (error) => {
      this.isLoading = false;
      console.log(error);
    }
  );}


ngOnInitAfterTimeout() {
    this.winRef.nativeWindow.SetCustomLayers(this.InputArray);

    this.winRef.nativeWindow.SetStartLayers();

    this.loadMapState();

    this.cleanup();

    this.customerMasterData();}


customerMasterData() {

if (this.showAsList) {
  // LIST

  if (this.reverse == false) {
    this.sortDirection = 'A';
  } else {
    this.sortDirection = 'D';
  }

  // string used for filtering the dataset
  let filterString = "";
  if (this.portfolioCB) {
    filterString += 'portfolio-';
  }
  if (this.rentalCB) {
    filterString += 'rental-';
  }
  if (this.emergencyCB) {
    filterString += 'emergency-';
  }

  this.dataService.customerMasterData(filterString, this.order, this.sortDirection, this.datePipe.transform(this.startdate, 'dd-MM-yyyy'), this.datePipe.transform(this.enddate, 'dd-MM-yyyy'), false, this.Globalvariables.emergencyDistance, this.listPage, this.specificTime)
    .subscribe(
      (response: Response) => {
        this.listViewData = response.json();
        this.getMarkers();
        this.listPageCount = Math.ceil(this.listViewData.totalFileViewCount / 50);
        if (this.listPageCount == 0) {
          this.listPageCount = 1;
        }
      },
      (error) => {
        console.log(error);
      }
    )
} else {
//MAP

  let filterString = "";
  if (this.portfolioCB) {
    filterString += 'portfolio-';
  }
  if (this.rentalCB) {
    filterString += 'rental-';
  }
  if (this.emergencyCB) {
    filterString += 'emergency-';
  }

  this.dataService.customerMasterData(filterString, this.order, this.sortDirection, this.datePipe.transform(this.startdate, 'dd-MM-yyyy'), this.datePipe.transform(this.enddate, 'dd-MM-yyyy'), false, this.Globalvariables.emergencyDistance, null, this.specificTime)
    .subscribe(
      (response: Response) => {
        this.listViewData = response.json();
        this.getMarkers();
      },
      (error) => {
        console.log(error);
      }
    )
}}

1 Ответ

0 голосов
/ 18 мая 2018

Вы должны использовать RxJS mergeMap, он делает то же самое, что вы ожидаете здесь.Выполнение одного http-вызова за другим ИЛИ Цепочка.

В вашем случае, на ngOnInit

ngOnInit() {
    this.dataService.portfolioPolygon()
      .map((response: Response) => {
          const data = response.json();
          // Do the rest
          },
       )
     .mergeMap(responseFromPortfolioPolygon => this.dataService.customerMasterData(filterString, this.order, this.sortDirection, this.datePipe.transform(this.startdate, 'dd-MM-yyyy'), this.datePipe.transform(this.enddate, 'dd-MM-yyyy'), false, this.Globalvariables.emergencyDistance, this.listPage, this.specificTime))
      .map(
       (res: Response) => res.json()
       // Do the rest
       )
       .subscribe(res => loadMap()  // CALL LOAD MAP );
}

Не забудьте импортировать mergeMap из правильного местоположения, так как это меняется в каждой RxJS версии

import 'rxjs/add/operator/mergeMap';

Надеюсь, это поможет.

...