Angular 服务未在延迟加载组件中初始化

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

我有一个 Angular 应用程序,其中有一个带有表格的组件。当我单击表格时,我想使用路由器更改视图并将该行传递给其他组件。我正在使用共享的可注入服务来执行此操作,但是我的组件是延迟加载的,因此该服务在启动时未初始化。

我的解决方案是创建一个超时,以便在我告诉共享服务传递单击的行之前初始化组件及其服务。这是最好的解决方案吗?下面的代码片段。

onRowClicked(row: any) {
    // first let's switch to the review application view so the sharedService gets initialized
    this.router.navigate(['review']);

    // give it 100 milliseconds to initialize then pass the selected row to the sharedService
    setTimeout(() =>{
      this.sharedService.change(row); // pass selected item
    }, 100);

  }
angular angular-services
1个回答
0
投票

您可以将服务更改为

providedIn: 'root'
,这将确保所有模块都有相同的服务实例!

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class SharedService {

  constructor() { }

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