【问题标题】:Access Service variable in AppModule in Angular在 Angular 的 AppModule 中访问服务变量
【发布时间】:2021-02-24 03:35:47
【问题描述】:

我正在我的 Angular 10 应用程序中实现 ngx-google-analytics,但此模块需要以这种方式实现 GA 跟踪代码:

NgxGoogleAnalyticsModule.forRoot(environment.ga)

而不是环境变量或硬编码代码。我希望使用共享服务从数据库中获取它,然后在此处访问该变量。但在 appmodule 中无法实现。

按照@Nayan 的建议,我尝试了这个解决方案:

How to inject an service into module in my case?

像这样:

export class AppModule { 
  constructor(private pubService: PubService) {
    console.log(this.pubService.StoreData);
    gcCode = this.pubService.StoreData['accessCodes'].filter(res => {
      res.codeName === 'gccode'
    }).codeValue;
  }
}

但就我而言,我已经使用了

{ provide: APP_INITIALIZER, useFactory: initializeApp, deps: [AppInitService], multi: true},

初始化服务并在实际从数据库中获取数据的服务之前加载构造函数。

我应该以这种方式初始化服务吗?或者还有其他方法吗?

尝试使用带有 Promise 和 observables 的构造函数,但是一旦我上线,api 调用需要时间并且应用程序在此之前加载。我可以使用超时,但我不想这样做。

export class AppModule { 
  constructor(private http: HttpClient) {
    // this.GetData().subscribe(res => {
    //   gcCode = res.filter(d => d.codeName == 'gccode')[0].codeValue;
    // });
    this.GetData();
  }

  GetData() {
    const url = (environment.apiURL+ '/api/pub/GetCodes');
    const promise = this.http.get(url).toPromise();
    promise.then((res: Array<any>) => {
      gcCode = res.filter(d => d.codeName == 'gccode')[0].codeValue;
    }).catch((error)=> {
      console.log(error);
    })
  }
}

【问题讨论】:

标签: angular ng-modules


【解决方案1】:

您可以使用手动方法。使用此代码从 main.ts 引导您的 Angular 应用程序

platformBrowserDynamic()
  .bootstrapModule(AppModule)
  .catch(err => console.error(err));

在调用 bootstrapModule 之前,您的 Angular 应用程序尚未初始化。 您可以轻松地将您的逻辑放在这里。

喜欢

fetch('api/path')
  .then(res => res.json())
  // Here you need to use any static prop or some global variable
  // because there is no DI yet
  .then(({key}) => MyService.key = key)
  // Bootstrap app when the key was fetched
  .then(() => 
    platformBrowserDynamic()
      .bootstrapModule(AppModule)
  )
  .catch(err => console.error(err));

然后在你的模块中使用获取的密钥。

APP_INITIALIZER 在解析模块导入后将永远无法工作。

【讨论】:

  • 谢谢@sergey 让我试试这个然后回复你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多