如何在Angular 7中设置静态文件的基本路径?

时间:2019-06-12 08:40:18

标签: angular angular7 angular-routing angular7-router

我尝试了三种方法。

第一名:index.html

<base href="/customer">

第二名:app.module.ts

@NgModule({
  providers: [{provide: APP_BASE_HREF, useValue: '/customer'}]
})

第3个:app-routing.module.ts

const routes: Routes = [
  { path: "", redirectTo: "/customer", pathMatch: "full" },
  {
    path: "customer",
    component: CustomerComponent,
    data: { animation: "HomePage" }
  }
];

以上所有方法都可以很好地用于URL路由,并且我得到了所需的URL。

http://localhost:4200/customer

但是,静态文件(js和图像)仍使用基本路径“ http://localhost:4200/”加载。我需要它像http://localhost:4200/customer/main.js

因此,出于某些安全的验证原因,我试图将其设置为http://localhost:4200/customer/main.js而不是http://localhost:4200/main.js

在下面的屏幕截图中可以看到相同的内容。

enter image description here

4 个答案:

答案 0 :(得分:1)

您可以将--baseHref命令行标志与ng serveng build一起使用,这意味着您不再需要为app-routing.module.ts中的路由添加前缀

ng serve --baseHref=/customer/

使用

构建
ng build --baseHref=/customer/

答案 1 :(得分:0)

  1. 使用'ng build --prod'进行Angular生产构建

  2. 打开index.html文件,并将<base href="/customer">插入<head></head>标记内。

答案 2 :(得分:0)

当我从角度5迁移到7时,我遇到了完全相同的错误。这可能与角度附加构建js文件的方式有关。如果您已经将<base href="/">添加到index.html中,但是脚本仍从相对路径加载,则可能是因为没有<body>标签。尝试将<body>标签添加到index.html文件中,看看它是否有效。

答案 3 :(得分:0)

您可以在 --deploy-url 命令中使用 ng build 参数。

示例:ng build --deploy-url /my/assets

有关 https://angular.io/guide/deployment 的更多详细信息。