Angular - 如何在 app.module 中的 forRoot 内动态传递环境值?

问题描述 投票:0回答:1

我想传递从 app.module 中相关环境文件 (env.json) 获取的值,但这些值在 GtmModule 初始化时不可用(初始化后几毫秒可用)。

我想问应该用什么方法来实现价值。我尝试过 @Inject 和自定义工厂,但没有运气。

GtmModule.forRoot({
      debug:environment.gaAnalyticsDebug,
      disabled:environment.gaAnalyticsDisabled, // GETTING UNDEFINED HERE
      gtmId: 'XXXX',
      readExtIdCookie: false,
    }),
angular environment-variables inject
1个回答
0
投票

创建单独的环境文件:

环境.staging.ts:

export const environment = {
  production: false,
  gaAnalyticsDebug: 'https://api.staging.com'
};

在你的 angular.json 文件中:

"configurations": {
  "staging": {
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.staging.ts"
      }
    ]
  },
}

在你的 app.module.ts 中:

import { environment } from '../environments/environment';

@NgModule({
  declarations: [
    // ...
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    MyServiceModule.forRoot({
      apiUrl: environment.gaAnalyticsDebug,
      // other dynamic values from environment
    }),
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}
© www.soinside.com 2019 - 2024. All rights reserved.