等待组件的数据加载,然后渲染下一个组件-Angular

时间:2020-02-07 15:11:08

标签: angular typescript rxjs angular2-observables rxjs-observables

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

我要遵循的方法-我在所有这些组件之间共享服务,并且每当为任何组件加载数据时,该组件都会在我的服务的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上调用了该方法,这不是预期的行为。任何帮助将不胜感激。提前致谢 !

1 个答案:

答案 0 :(得分:0)

问题:

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


修复

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

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

  2. 使用 await 创建 async 函数,以更新 bladeTracker 的值>仅在加载数据时。

  3. 编写一个名为“ showNextBlade() ”的函数,只要 bladeTracker 的值都会触发>元素更改。