本文介绍了forRoot方法中的角调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题是我在forRoot方法内部调用了一个函数,如下所示:
The problem is that I'm calling a function inside forRoot method like this:
app.module.ts
import {environment} from '../environments/environment';
...
@NgModule({
imports: [
BrowserModule,
MyModule.forRoot({
config: {
sentryURL: environment.SENTRY_URL <-- This, calls the function
}
}),
HttpClientModule,
...
]})
environemnt.ts
export function loadJSON(filePath) {
const json = loadTextFileAjaxSync(filePath, 'application/json');
return JSON.parse(json);
}
export function loadTextFileAjaxSync(filePath, mimeType) {
const xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', filePath, false);
if (mimeType != null) {
if (xmlhttp.overrideMimeType) {
xmlhttp.overrideMimeType(mimeType);
}
}
xmlhttp.send();
if (xmlhttp.status === 200) {
return xmlhttp.responseText;
} else {
return null;
}
}
export const environment = loadJSON('/assets/config.json');
配置如下:
{
"production": "false",
"SENTRY_URL": "https://[email protected]/whatever/1"
}
当我使用aot进行构建时,它说:
When I do the build with aot, it says:
任何想法??
:)
更新的解决方案:
我的最终解决方案是在应用程序中,使用Suren Srapyan所说的功能获取器。在库中,forRoot方法应如下所示:
My final solution is, in the app, use function getters as Suren Srapyan said. In the library, the forRoot method should look like this:
export const OPTIONS = new InjectionToken<string>('OPTIONS');
export interface MyModuleOptions {
config: {
sentryURLGetter: () => string | Promise<string>;
}
}
export function initialize(options: any) {
console.log('sentryURL', options.config.sentryURLGetter());
return function () {
};
}
@NgModule({
imports: [
CommonModule
]
})
export class MyModule {
static forRoot(options: MyModuleOptions): ModuleWithProviders {
return {
ngModule: MyModule,
providers: [
{provide: OPTIONS, useValue: options},
{
provide: APP_INITIALIZER,
useFactory: initialize,
deps: [OPTIONS],
multi: true
}
]
};
}
}
:D
推荐答案
@Decorators
不支持函数调用。或者,您可以获取 @NgModule
之外的值,然后使用该值。
Function call is not supported in the @Decorators
. Alternative you can get the value outside @NgModule
and than use it's value.
export function getSentryUrl() {
return environment.SENTRY_URL;
}
@NgModule({
imports: [
BrowserModule,
MyModule.forRoot({
config: {
getSentryURL: getSentryUrl
}
}),
HttpClientModule,
...
]})
这篇关于forRoot方法中的角调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!