Angular New Router remove /# from URL

2019-07-29 18:44发布

问题:

I'm on angular 1.4.6 and new router version 0.5.3 and wanted to remove the '/#' from the url. Can't seem to find anything about it on the Internet.

Edit: $locationProvider.html5mode(true); gives the following error: Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to: TypeError: $locationProvider.html5mode is not a function

回答1:

You can remove Hashtag from URLs only in browsers that support HTML5 History API. As you can see here, it's not supported in IE9, so in that case it will fallback to Hashtags.

Having said that, to make your URLs pretty in browsers that do support, you can enable html5Mode using $locationProvider config like below.

  angular.module('myApp', [])  
         .config(function($locationProvider){
             $locationProvider.html5Mode(true);
         });

In addition to this, you need to define the base URL of your application for the angular-router to identify the routes. If your URL is

http://localhost:8080/myApp/#showLogin
http://localhost:8080/myApp/#showHomePage

then you need to define the base URL using <base> tag like below

<head>
    <base href="/myApp">
</head>

Hope this helps :)



回答2:

Taken from Scotch.io

$locationProvider.html5Mode(true);