Routing doesn't work for me when doing a hard refresh

Issue

I was looking at this source code: https://github.com/angular/angular.io/blob/master/public/docs/_examples/toh-5/dart/lib/app_component.dart

and it seems that my application will route right now when i go to the root.

localhost:8080/

The routing updates as i move around my application, but it seems that if i am at something: localhost:8080/dashboard in a basecase, and do a hard refresh, it fails. It will give me a 404 not found! error.

It will work just find if i do: localhost:8080/#!/dashboard but that is not the address passed into my application.

In the index.html i have: <base href="/">

My App_Component.dart file is as follows:

import 'package:angular2/angular2.dart';
import 'package:angular2/router.dart';

import 'hero_component.dart';
import 'heroes_component.dart';
import 'dashboard_component.dart';
import 'hero_service.dart';
@Component(
    selector: "my-app",
    directives: const [ROUTER_DIRECTIVES],
    providers: const [HeroService, ROUTER_PROVIDERS],
    templateUrl: "app_component.html")
@RouteConfig(const [
  const Route(
      path: "/dashboard",
      name: "Dashboard",
      component: DashboardComponent,
      useAsDefault: true),
  const Route(
      path: "/detail/:id", name: "HeroDetail", component: HeroDetailComponent),
  const Route(path: "/heroes", name: "Heroes", component: HeroesComponent)
])
class AppComponent {
  String title = "Tour of Heroes";
}

It seems I have routing working for everything except this.

My desired end state would be doing: localhost:8080/detail/14 and it would open the correct component. This is something that isnt done now on a fresh site reference as much as when navigating throughout the application.

Solution

To switch to HashLocationStrategy change the providers to

bootstrap(AppComponent, [
  HeroService, 
  ROUTER_PROVIDERS,
  provide(LocationStrategy, useClass: HashLocationStrategy)
])

If you want to use PathLocationStrategy you can use this pub serve-wrapper https://pub.dartlang.org/packages/pub_serve_rewrites that allows to use PathLocationStrategy with pub serve.

For deployment you need to configure the webserver you use there to support HTML5 pushState.

Answered By – Günter Zöchbauer

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.