3

I wrote a simple Angular 2 application. Everything works just fine except one thing. When I click on the router link, Url is changed and component is loaded, then when I reload the page I get 404 not found. Can not understand why?

Here is my code:

(function(app) {


  app.AppComponent =
    ng.core.Component({
      selector: 'my-app',
      template: '<a [routerLink]="[\'Component1\']">Component1</a>' + 
                '<a [routerLink]="[\'Component2\']">Component2</a>' + 
                '<router-outlet></router-outlet>',
      directives: [
            ng.router.ROUTER_DIRECTIVES
      ]
    })
    .Class({
      constructor: function() {}
    });


    app.AppComponent = ng.router.RouteConfig([

    {
        path: '/component1', component: app.Component1, name: 'Component1' 
    },
    {
        path: '/component2', component: app.Component2, name: 'Component2' 
    }
    ]) ( app.AppComponent );


})(window.app || (window.app = {}));

Any help will be appreciated!

andrey
  • 1,867
  • 3
  • 21
  • 34

1 Answers1

5

That's a browser feature.
Angular by default uses HTML5 pushstate (PathLocationStrategy in Angular slang).
You either need a server that processes all requests like it were requesting index.html or you switch to HashLocationStrategy (with # in the URL for routes) https://angular.io/docs/js/latest/api/router/HashLocationStrategy-class.html

See also https://ngmilk.rocks/2015/03/09/angularjs-html5-mode-or-pretty-urls-on-apache-using-htaccess/

To switch to HashLocationStrategy use

bootstrap(AppCmp, [
  ROUTER_PROVIDERS,
  provide(LocationStrategy, {useClass: HashLocationStrategy})
]);

ensure you have all required imports

import {provide} from 'angular2/angular2';
import {
  HashLocationStrategy
  LocationStrategy,
  ROUTER_PROVIDERS,
} from 'angular2/router';
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I am using below code for hashlocation: ng.platform.browser.bootstrap(app.AppComponent, [ ng.router.ROUTER_PROVIDERS, , ng.core.provide(ng.common.LocationStrategy, { useClass : ng.common.HashLocationStrategy }) ]); but I am getting Cannot read property 'getOptional' of undefined error @Gunter – chikka.anddev May 18 '16 at 07:53