Angular2路由在重新加载页面

时间:2016-06-03 13:59:22

标签: angular dart

我已经编写了我的第一个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 {}

DashboardPage:

@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

enter image description here

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

 // 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事件绑定到角度路由器中,这样如果我刷新http://localhost:8080/#/home它实际上路由到HomeComponent?

1 个答案:

答案 0 :(得分:2)

void walkTree(Closure fn) { //Closure executed here if (this.leaf) leafCount++ for (child in children) { //closure passed as argument to walkTree method of child TreeNodes child.walkTree { node -> if (node.leaf) leafCount++ } } } 移除ROUTER_PROVIDERS,,您已在AppComponent中删除了bootstrap()ROUTER_PROVIDERS只能提供一次。