How to use environment variable in index.html for Angular 6

不羁岁月 提交于 2019-12-05 09:21:06

问题


I am using angular6, in my project I am using Facebook Account Toolkit for mobile verification purpose.

I need to initialise Account toolkit in index.html file using following code.

  AccountKit.init({
   appId:"XX",
   state:"xx",
   version:"v1.2",
   fbAppEventsEnabled:true,
   debug:true
 });

The problem is, values for appId and state change depending on environment (development/test/production).

How can I use environment variables in index.html file.

Please let me know if anyone has a solution for angular 6.

Thanks in advance.


回答1:


You should create copy of index.html and name it index.someenv.html. Then in your angular.json in environment configuration setup file replacement:

"fileReplacements": [
    {
        "replace": "src/index.html",
        "with": "src/index.someenv.html"
    }
]

The angular cli will replace these files when you run your build




回答2:


In main.ts file you can use document.write(environment.variable) and it will write what you want in index.html

(I use it to make the Google Analytics script take a dynamic Tracking ID wether it's in development or production mode, and it works well in Angular6)




回答3:


I think you can do it all in main.ts

const env = environment;

 AccountKit.init({
   appId:env.appId,  // this lane
   state:env.state,  // this lane
   version:"v1.2",
   fbAppEventsEnabled:true,
   debug:true
});

Thanks.




回答4:


An example here for document.write(environment.variable) : https://github.com/angular/angular-cli/issues/4451#issuecomment-285026543

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

if (environment.production) {
  document.write('<script type="text/javascript">// ProductionAnalyticsCodeHere</script>');
} else if (environment.staging) {
  document.write('<script type="text/javascript">// StagingAnalyticsCodeHere</script>');
}



回答5:


import your environment file into .ts file.

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

Create required fields in your class, assign values from environment to these variables in the constructor, use usual binding in the .html file.

.ts

import { Component } from '@angular/core';
import { environment } from '../environments/environment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public production = true;
  constructor() {
    this.production = environment.production;
  }
}

.html

<span>{{production}}</span>


来源:https://stackoverflow.com/questions/52050519/how-to-use-environment-variable-in-index-html-for-angular-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!