[英]Set imports from app.module by getting data from backend
In Angular is it possible to set imports from app.module by getting data from backend?在 Angular 中,是否可以通过从后端获取数据来设置从 app.module 导入?
RecaptchaFormsModule,
NgxStripeModule.forRoot(CONFIG.stripeKey),
AgmCoreModule.forRoot({
apiKey: CONFIG.keyFromDServer,
libraries: ["places"]
}),
So set the CONFIG.keyFromDServer with a key from the server.因此,使用来自服务器的密钥设置 CONFIG.keyFromDServer。 Can APP_INITIALIZER do this, if so how or is there anyway? APP_INITIALIZER 可以做到这一点,如果是这样,或者无论如何?
AOT compilation does not allow non-statically analyzable values to be used in Angular decorators. AOT 编译不允许在 Angular 装饰器中使用非静态可分析的值。
There are several options.有几种选择。 Here is one that waits for the configuration from the server before boostrapping the application.这是一个在 boostrapping 应用程序之前等待来自服务器的配置。
// main.ts
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { configurationToken } from './app/configuration';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
// Platform creation and bootstrapping of the application is delayed
// until we have loaded the configuration file.
fetch('/assets/configuration.json')
.then(configuration =>
platformBrowserDynamic([
{ provide: configurationToken, useValue: configuration },
]).bootstrapModule(AppModule))
.catch(error => console.error(error));
// configuration.ts
import { InjectionToken } from '@angular/core';
// We create an interface for the configuration JSON object
export interface Configuration {
readonly apiUrl: string;
readonly timezone: string;
readonly websocketUrl: string;
}
// We use a dependency injection token to access the configuration
// in our application.
export const configurationToken = new InjectionToken('Configuration');
// time.service.ts
import { Inject, Injectable } from '@angular/core';
import { Configuration, configurationToken } from './configuration';
@Injectable()
export class TimeService {
constructor(
@Inject(configurationToken) private configuration: Configuration,
) {}
// Configuration is available synchronously since it's just an object
// that can be injected.
get timezone(): string {
return this.configuration.timezone;
}
}
More options in " Handling Angular environments in continuous delivery " by Kevin Kreuzer. Kevin Kreuzer 的“ 在持续交付中处理 Angular 环境”中的更多选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.