如何在angular2中为不同的环境实例设置不同的base_url

How to have different base_url for different environment instance in angular2

我的 index.html angular2 文件有以下内容:

我想要那个,当我在 (npm 运行 build) 默认模式(开发模式)中构建它时,它应该是

<base href="/">

但是当我在生产模式下构建它时 (npm 运行 build --target=production),它应该是

<base href="/new/">

我是 angular1 的专家,但是 angular2 的新手,但我试图在 index.ts 文件中为 base_url 添加一个变量,但这似乎不起作用。

我希望一定有更快的方法来解决这个问题,谁能帮忙。

您可以使用 APP_BASE_HREF 提供商来设置它的值

@NgModule({
  imports: [..],
  declarations: [..],
  providers: [{provide: APP_BASE_HREF, useValue: '/new/'}]
})
class AppModule {}

因为您使用的是 Angular CLI,它确实支持得很好

# Sets base tag href to /myUrl/ in your index.html
ng build --base-href /myUrl/
ng build -bh /myUrl/

您可以在 package.json 中更新脚本:

"scripts": {
  //...
  "start": "ng serve -bh /anotheUrl/",
  "build": "ng build -bh /myUrl/",
  //..
},

https://github.com/angular/angular-cli/wiki/build