1
votes

I have built an Angular2 app using Angular CLI which contains many routes. The application is working absolutely fine. I can navigate to all routes using links, using URL or using navigate function of router. I can refresh page in browser on any route any time.

But when I am trying to serve my app from dist/index.html using a separate web server (brackets IDE server on dev or express/nginx/apache2 in production), the application routing behavior is different.

Application flow workd fine but when it comes to hit the URL directly (for any route) or refreshing page on any route application displays Cannot GET /dashboard error. Here dashboard is my route name. I am getting the same error on refreshing page on any existing route page.

I guess the application is properly bootstraping from index.html only and not from anywhere in the application.

What I am doing wrong please help.

index.html

 <script>
        System.import('system-config.js').then(function () {
          System.import('main');
        }).catch(console.error.bind(console));
      </script>

main.ts

bootstrap(NgUnityAppComponent, [ HTTP_PROVIDERS, ROUTER_PROVIDERS ]);

ng-unity.component.ts file

 import { Component } from '@angular/core';
    import { RouteConfig, ROUTER_DIRECTIVES } from '@angular/router-deprecated';
    import {APP_ROUTES} from './ng-unity.routes';
    import { NavbarComponent, FooterComponent, AboutUsComponent } from './shared/index';
    import {NavbarService} from './shared/navbar/navbar.service';
    @RouteConfig(APP_ROUTES)
    @Component({
        moduleId: module.id,
        selector: 'ng-unity-app',
        templateUrl: 'ng-unity.component.html',
        styleUrls: ['ng-unity.component.css'],
        directives: [ROUTER_DIRECTIVES, NavbarComponent, FooterComponent],
        providers:[NavbarService]
    })
    export class NgUnityAppComponent {

    }

What I am doing wrong? Please help.

1
stackoverflow.com/questions/31415052/… This explains the cause and solution.Rahul Bhooteshwar

1 Answers

0
votes

Make sure this is placed in the head element of your index.html:

The Example in the Angular2 Routing & Navigation documentation uses the following code in the head instead (they explain why in the live example note of the documentation):

When you refresh a page this will dynamically set the base href to your current document.location.