【发布时间】: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