首页 > 解决方案 > 如何等待服务准备好Angular?

问题描述

内部根组件初始化了第一次单音服务。

export class AppComponent {
  constructor(private reonMapLibraryService: ReonMapLibraryService) {
}
}

然后在子组件中,我尝试准备好实例:

export class SearchFilterComponent implements OnInit, AfterViewInit {
   constructor(private reonMapLibraryService: ReonMapLibraryService) {}
   ngAfterViewInit(): void {
    this.layers = this.reonMapLibraryService.layersManager.getRegistryTree();
  }
}

它说reonMapLibraryServiceundefined,因为首先加载了子组件。

如何等待子组件的服务?

标签: angularangular5angular8

解决方案


如果您需要在应用程序初始化之前等待准备就绪的服务或异步预取一些数据,那么最好的地方是APP_INITIALIZER。应用程序应在初始化程序执行期间等待,并且仅在初始化程序解决后才会启动。您可以像这样使用它(让我们将初始化程序放在 AppModule 中):

export function init_app(reonMapLibraryService: ReonMapLibraryService) {
  return async () => await reonMapLibraryService.fetchData();
}

@NgModule({
  declarations: [...],
  imports: [...],
  providers: [
    ...,
    ReonMapLibraryService,
    {
      provide: APP_INITIALIZER,
      useFactory: init_app,
      deps: [ReonMapLibraryService],
      multi: true
    }
  ]
})

而已。它应该等待fetchData方法执行并仅在解决后引导应用程序。


推荐阅读