Angular:通过环境设置 APP_BASE_HREF 无效

标签 angular angular-cli

在我的 Angular 应用程序中,我想使用环境来设置 <base href="">自动。

我的 app.module.ts 中有以下相关行:

...
import { APP_BASE_HREF } from "@angular/common";
import { environment } from "../environments/environment";
...

...
providers: [
    { provide: APP_BASE_HREF, useValue: environment.baseHref },
    ...
  ]
...

这是我的环境文件:

environment.ts :

export const environment = {
  ...,
  baseHref: "/app/"
};

environment.prod.ts :

export const environment = {
  ...
  baseHref: "/"
};

但是,当使用 ng build 时或 ng build --prod ,这两个配置都没有应用于生成的 index.html .

我的配置:

  • 操作系统:Windows 10 x64
  • Angular v4.2.4
  • Angular CLI v1.1.1

感谢您抽出宝贵时间!

最佳答案

那是因为 APP_BASE_HREF仅与 PathLocationStrategy 一起使用, 它不会改变 index.html 基础 href。您应该为该 --base-href 使用命令行选项:

ng build --prod --base-href /

来自指南:

Some developers may not be able to add the element, perhaps because they don't have access to or the index.html.

Those developers may still use HTML5 URLs by taking two remedial steps:

  • Provide the router with an appropriate APP_BASE_HREF value.
  • Use root URLs for all web resources: CSS, images, scripts, and template HTML files.

关于Angular:通过环境设置 APP_BASE_HREF 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44774885/

相关文章:

javascript - Angular 5 : Access element inner html from the component for dynamically generated elements

asp.net - 带有 ASP NET MVC 的 Angular Cli

angular - "port 4200 already in use"错误,尽管它没有被使用

angular - Angular 如何构建和运行

Angular CLI 版本与 Angular 版本不兼容

Angular - ErrorHandler 中的导航仅适用于 zone.run()

javascript - 如何使用 Node.js 服务器部署 Angular 5 应用程序

node.js - 我在 Angular 2 的 npm install 上遇到问题

angular - 如何将复选框值分配给 Angular 表单控件名称?

angular - 在 Angular 中包含导航栏的最佳方式?