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



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

我正在遵循的方法 - 我在所有这些组件之间有一个共享服务,每当为任何组件加载数据时,该组件都会在我的服务的行为主题上调用下一个方法 -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 循环会前进。因此,它将循环变量设置为最后一个值,并在最后一个组件实例上调用该方法,这不是预期的行为。任何帮助将不胜感激。提前感谢!

问题:

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


修复

此问题可以通过3个步骤解决,如下所示:

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

  2. 创建一个在数据加载时
  3. 具有等待异步函数,该函数仅在加载数据时更新bladeTracker的值。

  4. 编写一个名为">showNextBlade((">的函数,每当bladeTracker元素的值发生变化时,它就会被触发。

相关内容

最新更新