Set base href from an environment variable with ng

2019-03-10 22:12发布

问题:

Does anyone know how to accomplish this with the angular-cli? I would like to be able to store the baseHref path in an environment variable within /src/environments/environment.x.ts and based on the selected evironment during build, be able to set the baseHref path.

Something like this:

environment.ts

export const environment = {
  production: false,
  baseHref: '/'
};

environment.prod.ts

export const environment = {
  production: true,
  baseHref: '/my-app/'
};

And then call...

ng build --prod

...and have my /dist/index.html file show <base href="/my-app/">.

I thought maybe if I named my environment variable the same as the --base-href build option used in the build command that the cli might pick it up, but no dice there either.

Is there someway to reference an environment variable from the command line? Something like ng build --base-href environment.baseHref?

回答1:

You would have to use APP_BASE_HREF

@NgModule({
  providers: [{provide: APP_BASE_HREF, useValue: environment.baseHref }]
})
class AppModule {}

See angular doc

EDIT

Since CSS/JS does not work with APP_BASE_HREF, you can do this:

In app.component.ts, inject DOCUMENT via import {DOCUMENT} from "@angular/platform-browser";

constructor(@Inject(DOCUMENT) private document) {
}

Then on your ngOnInit()

ngOnInit(): void {
    let bases = this.document.getElementsByTagName('base');

    if (bases.length > 0) {
      bases[0].setAttribute('href', environment.baseHref);

    }
  }