Angular2- When refresh the page, url remains same

2019-05-07 21:03发布

问题:

In Angular2, I am facing this issue. When you refresh the page. The URL remains same but it doesn't load appropriate view in RouterOutlet.

Everything works fine except refreshing page issue.

app.ts

import {Component,bind} from 'angular2/core';

import {bootstrap} from 'angular2/platform/browser';
import {FORM_DIRECTIVES} from 'angular2/form';
import{HomeCmp} from 'Angular/src/Home/home.ts';
import {ContactUsCmp} from 'Angular/src/ContactUs/contactus.ts';

import {Router,ROUTER_PROVIDERS,RouteConfig, ROUTER_DIRECTIVES,APP_BASE_HREF,LocationStrategy,RouteParams,ROUTER_BINDINGS} from 'angular2/router';
@Component({
selector: 'micropuppy-app',
templateUrl: "ANGULAR/Templates/home.html",
directives:[HomeCmp,ROUTER_DIRECTIVES,ContactUsCmp],
template: ` <nav>
                    <ul class="nav navbar-nav">
                    **<li><a [routerLink]="['Home']">One</a><hr/></li>
                     <li><a [routerLink]="['ContactUs']">Contact Us</a></li>**
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Technologies <span class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li><a href="#">Angular</a></li>
                            <li><a href="#">.NET</a></li>
                        </ul>
                    </li>
            </ul>
        </nav>

    <router-outlet></router-outlet>`
 })

@RouteConfig([
  {path:'/Home', name: 'Home', component: HomeCmp}
  {path:'/ContactUs', name: 'ContactUs', component: ContactUsCmp}
])

export class MicropuppyApp {
    constructor(){
        console.log("Micropuppy app started");
    }
}
 bootstrap(MicropuppyApp, [ROUTER_PROVIDERS,bind(APP_BASE_HREF).toValue(location.pathname)]);

回答1:

With the default strategy (HTML5 history API) of routing, you need a server configuration to redirect all your paths to your HTML entry point file. With the hashbang approach it's not necessary... If you want to switch to this approach, simply use the following code:

import { bootstrap } from "angular2/platform/browser";
import { provide } from "angular2/core";
import {
  ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy
} from "angular2/router";

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

You could have a look at these questions about this issue:

  • When I refresh my website I get a 404. This is with Angular2 and firebase
  • PathLocationStrategy vs HashLocationStrategy in web apps
  • Is Angular 2's Router broken when using HTML5 routes?

Hope it helps you, Thierry



回答2:

Even I was stuck in the same situation where on refresh Angular2 app was failing to load.

The reason behind this issue is Angular2 router uses history API for routing due to which on the refresh of route App unable to find index.html and end up showing 404 or can not GET requested URL.

you can work around in two ways:

  1. Hashbang technique by using HashLocationStrategy but URL looks bad due to present of hash.

  2. Here how I worked it out:

I use Node.js for serving the request.

Assuming you have Node and Npm installed.

package.json for installing required modules.

{
  "name": "Express server",
  "version": "",
  "dependencies": {
    "express": "^4.14.0"
  }
}

create server.js in your project directory.

var express = require('express');
var app = express();

app.use(express.static('dist')); 
// 'dist' is my build folder, you can add yours. this will take care of all static files.

app.use('/*', express.static('dist/index.html')); 
// This will make sure that every route should serve index.html first 

app.listen(8080, function () {
    console.log('app listening on port 8080!!')
});

Use the following command to start your app server.

node server.js

Now every request will go through your App server which will make sure that on every refresh/reload index.html get served which will boost angular App.



回答3:

I managed to fix this issue by putting this code on the top of head in the index.html under <title> put

<script>document.write('<base href="/" />');</script>


回答4:

This is not the right answer but On-refresh you can redirect all dead calls to Homepage by sacrificing 404 page it's a temporary hack just replay following on 404.html file

   <!doctype html>
<html>
    <head>
        <script type="text/javascript">
            window.location.href = "http://" + document.location.host;
        </script>
    </head>
</html>


回答5:

If you don' want # means, go with 'PathLocationStrategy'. It is somewhat similar to HashLocationStratedy. Hope, this link will help you Angular2 routing.