等待渲染下一个组件之前加载组件的数据-角度

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

我必须渲染一个组件链(例如刀片中的网格),其中在加载第一个组件的数据之后,我将单击该组件的数据行,然后它将打开下一个组件。单击下一个组件的数据行时,它将打开另一个组件,依此类推。

我正在遵循的方法-我在所有这些组件之间拥有共享服务,并且无论何时为任何组件加载数据,该组件都会在我的服务的BehaviourSubject上调用next方法-this.service.dataLoadedEvent$.next(componentName)

我的服务方法看起来像-

public renderAllComponents(selectedOption, componentsToRender, componentsInfo): void {
    let componentInstance;

    for (let i = 0; i < componentsToRender.length; i++) {
      componentInstance = new componentsToRender[i](this);

      if (i === 0) {
        // For the component in the first/initial blade
        this.addFirstComponent(componentInstance[i]);
      }
      this.dataLoadedEvent$.subscribe((val) => {
         if (val === componentsInfo[i].name) {
           componentInstance.onSelect(selectedOption[componentsToRender[i].name]);
         }
      });
    }
  }

组件看起来像-

 public ngOnInit() {
    this.view = this.comp.pipe(
      tap(state => {
        this.isLoading = true;
      }),
      switchMap(state => {
        return this.orderService.fetch(state);
      }),
      tap(() => {
        this.isLoading = false;
        this.service.dataLoadedEvent$.next(this.constructor.name);
      })
    );
  }

但是这里的问题是,在通知服务有关数据加载完成之前,for循环前进。因此,它将循环变量设置为最后一个值,并且在最后的componentInstance上调用了该方法,这不是预期的行为。任何帮助将不胜感激。提前致谢 !

angular typescript rxjs angular2-observables rxjs-observables
1个回答
0
投票

问题:

循环中的迭代将异步执行,因此,等待值不会发生。


修复

此问题可以通过以下三个步骤来解决:

  1. 创建ID为'bladeTracker的隐藏元素(Example: <i id="bladeTracker">1</i>)并将其值设置为初始刀片编号。

  2. [async函数,在数据加载时创建async函数,仅在加载数据时才更新bladeTracker的值。

  3. 编写一个名为'showNextBlade()'的函数,只要bladeTracker元素的值发生更改,就会触发该函数。

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