Angular 2 : 404 error occur when I refresh through the browser

标签 angular angular2-routing

<分区>

我已将我的单页应用程序存储在服务器中名为“myapp”的文件夹中。我已将 base 中的 URL 更改为 http://example.com/myapp/` .

我的项目有两个页面。所以我实现了 Angular 2 路由。我将默认页面设置为登录。当我在浏览器中键入 http://example.com/myapp/ 时,它会自动重定向到 http://example.com/myapp/login。但是,如果刷新该页面,我会收到 404 错误,提示未找到 http://example.com/myapp/login

但是如果我使用精简版服务器运行我的项目,一切正常。在这种情况下,index.html 中的基本 URL 将为 "/"。如何解决?

最佳答案

Angular 2 最终版更新

在 app.module.ts 中:

  • 添加导入:

      import { HashLocationStrategy, LocationStrategy } from '@angular/common';
    
  • 在 NgModule 提供者中,添加:

      {provide: LocationStrategy, useClass: HashLocationStrategy}
    

示例 (app.module.ts):

import { NgModule }       from '@angular/core';
import { BrowserModule  } from '@angular/platform-browser';
import { AppComponent }   from './app.component';
import { HashLocationStrategy, LocationStrategy } from '@angular/common';

@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule],
    providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],
    bootstrap: [AppComponent],
})
export class AppModule {}

备选

使用带有 {useHash: true} 参数的 RouterModule.forRoot。

示例:(来自 angular docs)

import { NgModule } from '@angular/core';
...

const routes: Routes = [//routes in here];

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(routes, { useHash: true })
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

关于 Angular 2 : 404 error occur when I refresh through the browser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35284988/

相关文章:

unit-testing - 测试 ionic2 组件 : No provider for Form

javascript - 如何从 Angular 2 的内部组件中路由?

javascript - 尾随 "="在 angular2 url 中被 trim

angular - 如何返回上一页

javascript - Angular 2 管道依赖注入(inject)

angular - Infragistics:如何使用 id 显示多个 ignite Snackbar

Angular LoadChildren 字符串格式已弃用,但函数格式会导致错误

Angular 2、Material 2 radio 、表单组

javascript - Angular 2 Routes - 是否可以使用 ngFor 从路由创建动态 routerLinks?

angular - 在 Angular 2 中订阅主/详细信息示例中的子路由更改