【问题标题】:Angular2 Routing gives 404 when reloading page重新加载页面时Angular2路由给出404
【发布时间】:2016-06-03 13:59:21
【问题描述】:

我已经编写了我的第一个 Angular Dart 应用程序,但是路由出了点问题......

@Component(
    selector: 'ahpmui',
    template: '''
        <strong>My First Angular 2 App - {{name}}</strong>
        <br />
        <router-outlet>
        </router-outlet>
        <br />
        <nav>
            <a [routerLink]="['HomePage']">Home</a> |
            <a [routerLink]="['DashboardPage']">Dashboard</a>
        </nav>
    ''',
    directives: const [ROUTER_DIRECTIVES],
    providers: const [
        ROUTER_PROVIDERS,
        HomePage,
        DashboardPage
    ]

)
@RouteConfig(const [
    const Route(path: '/dashboard', component: DashboardPage, name: 'DashboardPage', useAsDefault: true),
    const Route(path: '/home', component: HomePage, name: 'HomePage')
])
class AppComponent {

    String name = "Sample App";

}

主页:

@Component(
    selector: 'home-page',
    template: '<strong>This is the Home Page</strong>')
class HomePage {}

仪表板页面:

@Component(
    selector: 'dashboard-page',
    template: '<strong>This is the Dashboard Page</strong>')
class DashboardPage {}

main.dart:

// bootstrap angular2
    bootstrap(AppComponent, [
        ROUTER_PROVIDERS,
        provide(APP_BASE_HREF, useValue: '/'),
        provide(LocationStrategy, useClass: HashLocationStrategy)
    ]);

当我的应用程序启动时,它按预期转到http://localhost:8080/dashboard,当单击Home 链接时,它正确转到http://localhost:8080/home。如果我现在刷新页面,我会收到错误 404

然后我将引导部分更改为:

 // bootstrap angular2
    bootstrap(AppComponent, [
        ROUTER_PROVIDERS,
        provide(APP_BASE_HREF, useValue: '/#/'),
        provide(LocationStrategy, useClass: HashLocationStrategy)
    ]);

网址现在如下(我更喜欢这种风格,因为旧版应用程序使用相同的网址格式)

http://localhost:8080/#/dashboard
http://localhost:8080/#/home

如果我点击刷新,不再收到错误 404,但页面会重定向回 http://localhost:8080/#/dashboard 页面。

我正在使用 pub serve 运行应用程序

有什么方法可以将 onHashChange 事件绑定到 Angular 路由器,这样如果我刷新 http://localhost:8080/#/home 它实际上会路由到 HomeComponent?

【问题讨论】:

  • AFAIR URL 格式与HashLocationStrategy 一样。当您完全删除provide(APP_BASE_HREF, ...) 行时会发生什么(不确定HashLocationStrategy 是否需要它)。您能否也尝试将&lt;base href="/"&gt;(而不是provide(APP_BASE_HREF, ...))作为head 标签中的第一个元素?

标签: angular dart


【解决方案1】:

AppComponent 中删除ROUTER_PROVIDERS,,您已经在bootstrap() 中拥有它们。 ROUTER_PROVIDERS 只能提供一次。

【讨论】:

  • 使用 HashProvider 将 AppBaseHref 更改为 / 也为我提供了所需的 /#/home URL 格式:-D
  • 是的,正如预期的那样:D
猜你喜欢
  • 2021-06-05
  • 2020-06-20
  • 2019-07-20
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-13
相关资源
最近更新 更多