如何等待服务就绪Angular?

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

内部根组件首次被初始化为singltone服务。

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,因为首先ar加载了子组件。

如何等待子组件的服务?

angular angular5 angular8
1个回答
0
投票

如果需要在应用程序初始化之前等待即用型服务或异步预取一些数据,则最佳选择是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方法执行,并且只有在应用解析后才对其进行引导。

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