简体   繁体   English

如果环境角度是生产,则禁用组件

[英]Disable component if environment angular is production

I have something like this我有这样的事情

enviroment.ts环境.ts

export const environment = {
  production: false
};

And in app.module.tsapp.module.ts

I have something like this我有这样的事情

@NgModule({
  declarations: [AppComponent, VersionComponent],
  imports: [],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule { }

The problem I have is that based on environment.production i need to declare or not to declare VersionComponent我的问题是基于 environment.production 我需要声明或不声明VersionComponent

Something like this像这样的东西

if (environment.production) {VersionComponent}

The problem is that if is not allowed declarations , has someone had similar problem?问题是,如果不允许声明,有人有类似的问题吗?

Module metadata is consumed by the angular compiler, which only supports subset of JavaScript .模块元数据由 angular 编译器使用,它只支持JavaScript 的子集 Fortunately, that subset includes the conditional and spread operators, allowing us to write:幸运的是,该子集包括条件和扩展运算符,允许我们编写:

declarations: [
  AppComponent,
  ...(environment.production ? [VersionComponent] : []),
],

Or course, this may cause syntax errors if any templates make use of the undefined component ...或者当然,如果任何模板使用未定义的组件,这可能会导致语法错误......

Alternatively, you could replace the component with a different definition that has the same selector, but doesn't do anything:或者,您可以使用具有相同选择器但不执行任何操作的不同定义替换组件:

declarations: [
  AppComponent,
  environment.production ? VersionComponent : VersionComponentStub,
],
const declarations =  [AppComponent];
let extraDeclarations = [];
if(environment.production) {
    extraDeclarations = [VersionComponent]
}

const finalDeclarations = declarations.concat(extraDeclarations);
@NgModule({
    declarations: finalDeclarations
const _declarations = [AppComponent];

if( environment.production )
   _declarations.push( VersionComponent );

@NgModule({
  declarations: [
    _declarations
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

works for me ;)为我工作;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM