【问题标题】:Loading a page directly in Angular 6直接在 Angular 6 中加载页面
【发布时间】:2019-03-04 11:11:52
【问题描述】:

我有一个 Angular 6 应用程序,其中包含一个名为 assets 的组件。当我通过 routerLinks 导航到组件时,页面加载并按预期显示数据:

http://localhost:4200/assets/2

但是,如果我刷新页面,或者直接在浏览器中加载链接,那么我的很多脚本都无法加载:

GET http://localhost:4200/assets/runtime.js net::ERR_ABORTED 404 (Not Found)

Refused to execute script from '<URL>' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

GET http://localhost:4200/assets/polyfills.js net::ERR_ABORTED 404 (Not Found)

我需要在路由器中做些什么吗?或者是什么原因造成的?

【问题讨论】:

  • 考虑将此路由添加到您的路由器配置中。
  • 在您的路由模块上添加{useHash: true}。它看起来像这样:RouterModule.forRoot(routes, {useHash: true})。使用哈希,它将能够处理刷新。
  • @YgorAzevedo 你的建议做到了。能不能给个答案。感谢大家的帮助!

标签: angular


【解决方案1】:

在您的路由模块中启用哈希位置。它应该如下所示。

const routes: Routes = [
  { path: '', component: MyComponent },
  { path: 'my-other', component: MyOtherComponent }
];

@NgModule({
  exports: [ RouterModule ],
  imports: [ RouterModule.forRoot(routes, {useHash: true}) ]
})
export class MyRoutingModule { }

之后,Angular 将能够处理刷新。

【讨论】:

  • 你救了我的命。
  • 很高兴能帮上忙。
【解决方案2】:

这是因为,Angular 路由器默认使用 PathLocationStrategy。

http://localhost:4200/assets/2。当您刷新浏览器时,您需要重定向到主页(index.html),这应该在服务器端路由器重定向设置中处理。

您也可以尝试 HashLocationStrategy,即它会添加带有“#”的路由器路径。 http://localhost:4200/#assets/2。如果你遵循这个,你可以处理页面刷新。但是我们需要确保页面状态在所有模块中都可用,包括延迟加载模块。

【讨论】:

  • 感谢您回复所有@Suresh,Ygor 解决了这个问题。
【解决方案3】:

当您更改基本 href 值时也会出现此问题

<base href="/"> to Something else

在 index.html 中

【讨论】:

  • 这是我遇到的讨厌的问题。
【解决方案4】:

这似乎是一个 URL Re-write 问题。如果您有 iis 服务器,则需要将 web.config 文件放入服务器并添加 url 重写逻辑。你可以在angular.io找到它

如果你有 apache 那么你需要写你必须添加 [.htaccess][2]

[2]:Deploy Angular 2 to Apache Server 文件。

【讨论】:

  • 我正在使用 ng serve。
  • 您在哪个系统上工作? Windows 还是 Apache?
  • Windows 和 Angular CLI。
  • 那么请添加 web.config 并在下面添加逻辑
猜你喜欢
  • 2019-06-07
  • 2018-12-24
  • 2019-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多