Angular中AppModule中的Access Service变量



我正在Angular 10应用程序中实现ngx谷歌分析,但该模块需要GA跟踪代码以这种方式实现:

NgxGoogleAnalyticsModule.forRoot(environment.ga)

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

正如@Nayan所建议的,我尝试了这个解决方案:

在我的情况下,如何将服务注入模块?

像这样:

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应用程序是使用以下代码从main.ts启动的

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将永远不会在模块导入解析后服务解析时工作。

最新更新