- 在项目根目录下的environment.ts和environment.prod.ts文件中添加环境变量。
export const environment = {
  production: false,
  API_URL: 'http://localhost:3000/api'
};
- 在根模块app.module.ts中引入并使用environment.ts中的环境变量。
import { environment } from './environments/environment';
@NgModule({
  imports: [
    BrowserModule
  ],
  declarations: [
    AppComponent
  ],
  providers: [
    {
      provide: 'API_URL',
      useValue: environment.API_URL
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
- 在需要使用环境变量的组件中通过依赖注入方式获取环境变量。
import { Component, Inject } from '@angular/core';
@Component({
  selector: 'app-root',
  template: '{{ apiUrl }}'
})
export class AppComponent {
  apiUrl: string;
  constructor(@Inject('API_URL') apiUrl) {
    this.apiUrl = apiUrl;
  }
}