当直接转到 URL 时,AngularJS 路由路径中的参数不会以 HTML5 模式加载 [英] AngularJS routes with parameters in path not loading in HTML5 mode when going directly to URLs

查看:21
本文介绍了当直接转到 URL 时,AngularJS 路由路径中的参数不会以 HTML5 模式加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我指定了几条路线:

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);

}]);

当另一条路径上有一个链接到 /test/x 时,它工作正常.不在 HTML5 模式下也能正常工作.但是,当您在 HTML5 模式下直接导航到 /test/x 时,不会加载路由,并且不会执行 resolve 中的任何内容.

When there is a link on another route leading to /test/x, it works fine. It also works fine when not in HTML5 mode. However, when you navigate directly to /test/x in HTML5 mode, the route doesn't load and none of the stuff in resolve is executed.

我已经浏览了很多 AngularJS 文档,但仍然无法弄清楚这一点.lz :(

I've looked through much of the AngularJS documentation and still can't figure this out. plz :(

我做了更多测试,这仅适用于其中有斜线的路由.是否有参数(如 :id)似乎并不重要.转到 /hello(如果定义了该路由)适用于 HTML5 和非 HTML5 模式下的所有情况.转到诸如 /hello/world 之类的内容始终在非 HTML5 模式下工作,当通过单击链接从另一条路线更改路线时,则在 HTML5 模式下工作.在 /hello/world 上刷新时,转到地址栏并按 Enter 键或单击指向它的其他网站的链接会导致它重新加载索引页面而不是实际路线.

I've done more testing, and this is only for routes that have a slash in them. It doesn't seem to matter if there is a parameter (like :id) in it or not. Going to /hello (if that route is defined) works for all cases in both HTML5 and non-HTML5 mode. Going to something like /hello/world always works in non-HTML5 mode and works in HTML5 mode when the route is changed from another route by clicking a link. Refreshing when on /hello/world, going to the address bar and pressing enter or clicking a link pointing to it from another website causes it to reload the index page but not the actual route.

推荐答案

添加到 部分是一种修复,具体取决于您遇到的问题.

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

(这是我的答案,所以我想确保让其他遇到此问题的人更明显)

(this was the answer for me, so I wanted to make sure to make it more obvious for others that run into this)

感谢@user27766 指出.

Thanks to @user27766 for pointing it out.

这篇关于当直接转到 URL 时,AngularJS 路由路径中的参数不会以 HTML5 模式加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆