3
votes

I've written my first Angular Dart app, but something is wrong wit the routing ...

@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";

}

HomePage:

@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)
    ]);

When my app starts up, it goes to http://localhost:8080/dashboard as expected, when clicking on the Home link, it correctly goes to http://localhost:8080/home. If I now refresh the page, I get an error 404

enter image description here

I then change the bootstrap part to this:

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

URLs are now as follow (I prefer it in this style since the legacy app is using this same url format)

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

If I hit refresh, no longer get the error 404, but the page redirects back to the http://localhost:8080/#/dashboard page.

I'm running the app using pub serve

Is there any way I can tie in the onHashChange event into the Angular Router so that if I refresh http://localhost:8080/#/home that it actually routes to the HomeComponent ?

1
AFAIR the URL format is like this with HashLocationStrategy anyway. What happens when you remove the provide(APP_BASE_HREF, ...) line entirely (not sure if it's required for HashLocationStrategy). Can you please also try <base href="/"> (instead of provide(APP_BASE_HREF, ...))as first element in the head tag?Günter Zöchbauer

1 Answers

2
votes

Remove ROUTER_PROVIDERS, from AppComponent, you have them in bootstrap() already. ROUTER_PROVIDERS should be provided only once.