【问题标题】:Using env variables in template files在模板文件中使用环境变量
【发布时间】:2018-09-21 15:05:54
【问题描述】:

是否可以在模板文件中使用环境变量?

我目前正在尝试这种语法:

<img class="preview-image" src="{{environment.assets + item.image}}" />

导致以下错误:

未定义标识符“环境”。组件 声明、模板变量声明和元素引用 不包含这样的成员

我尝试将它导入到我的 component.ts 文件中,import { environment } from './../../../../environments/environment'; 但它没有改变任何东西。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    只要在controller中定义publicenvironment变量的值,就可以在模板中访问:

    import { environment } from '../environments/environment';
    
    export class AppComponent {
    
      environment = environment;
    
    }
    

    【讨论】:

      【解决方案2】:

      我最近也想做同样的事情,我想出了一个适用于每个模板的管道解决方案,而无需更改其 .ts 文件:

      import {Pipe, PipeTransform} from '@angular/core';
      import {environment} from '../../environments/environment';
      
      @Pipe({name: 'env'})
      export class EnvPipe implements PipeTransform {
        transform(variable: string): any {
          return environment[variable];
        }
      }
      

      然后,在您的 HTML 中,只需使用:

      <span>{{'variableName' | env}}</span>
      

      在你的情况下:

      <img class="preview-image" src="{{'assets' | env}}{{item.image}}" />
      

      确保将管道组件添加到您的app.module.ts

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-12
        • 2021-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多