AngularJS routes with parameters in a path that does not load in HTML5 mode when navigating directly to URLs

I have several routes listed:

app.config(["$routeProvider", "$locationProvider", function($routeProvider, $locationProvider) { $routeProvider. when("/", { templateUrl: "/ajax/home.html", controller: "HomeController" }). when("/test/:id", { templateUrl: "/ajax/test.html", controller: "TestController", resolve: { data: function ($q, $http, $route) { var deferred = $q.defer(); var params = $route.current.params; $http({method: "GET", url: "/api/test/" + params.id + ".json"}) .success(function(data) { deferred.resolve(data) }) .error(function(data){ deferred.reject(); }); return deferred.promise; } } }); $locationProvider.html5Mode(true); }]); 

When there is a link to another route leading to /test/x , it works fine. It also works great if not in HTML5 mode. However, when you go directly to /test/x in HTML5 mode, the route does not load and none of the files in the resolution are executed.

I have looked through most of the AngularJS documentation and still cannot figure it out. plz: (

Edit: I did more testing, and this only applies to slash routes. It doesn't seem to matter if there is a parameter in it (e.g :id ) or not. Switching to /hello (if this route is defined) works for all cases both in HTML5 mode and not in HTML5. Going to something like /hello/world always works in a mode other than HTML5, and works in HTML5 mode when the route is changed from another route by clicking on the link. Updating when /hello/world enabled, navigating to the address bar and clicking on an entry or clicking on a link pointing to it from another website causes it to reload the index page, but not the actual route.

+4
source share
2 answers

Adding <base href="/" /> to the <head> section is a fix, depending on what problem you are experiencing.

(this was the answer for me, so I wanted to make sure that it would become more obvious to others who are faced with this)

Thanks to @ user27766 for pointing it out.

+5
source

The angular docs for the $ location service specify that using HTML5 mode requires the use of server side URL rewriting to rewrite all your links to your application’s entry point (e.g. index.html)

If you used Apache to service your application, you can configure the .htaccess file as follows:

 RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^test/[0-9]+$ index.html [L] 

This will redirect requests like /test/<number> in index.html and angular so that it can route it correctly.

0
source

Source: https://habr.com/ru/post/1489731/


All Articles