【问题标题】:Wait for data of a component to load before rendering the next component - Angular在渲染下一个组件之前等待组件的数据加载 - Angular
【发布时间】:2020-05-23 17:57:51
【问题描述】:

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

我正在遵循的方法 - 我在所有这些组件之间有一个共享服务,并且每当为任何组件加载数据时,该组件都会调用我服务的 BehaviourSubject 上的下一个方法 - 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】:

    问题:

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


    修复

    这个问题可以分3步解决,如下:

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

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

    3. 编写一个名为 'showNextBlade()' 的函数,该函数在 bladeTracker的值时触发> 元素变化。

    【讨论】:

      猜你喜欢
      • 2019-08-09
      • 1970-01-01
      • 1970-01-01
      • 2017-01-14
      • 1970-01-01
      • 2022-12-03
      • 2018-09-03
      • 2016-06-09
      • 2021-04-19
      相关资源
      最近更新 更多