【问题标题】:angularjs route not working without last slash /没有最后一个斜杠/
【发布时间】:2016-04-07 17:18:52
【问题描述】:

我已经这样配置了$routeProvider

miNgAppplication.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
        .when("/", {
            templateUrl: "Base/FirstPage",
            controller: "miNgControllerFirstPage"
        })
}]);

当我插入带有最后一个斜杠的网址时,这有效,例如“http://localhost/myApp/”。它在 URL 中添加“#/”并显示正确的内容(最终 URL 为“http://localhost/myApp/#/”)
当我不使用斜杠时它不起作用,基本上是因为它错误地更改了 URL
http://localhost/myApp”->“http://localhost/myApp#/”。

我该怎么办?我是否错误地使用了第一个 when 参数来定义第一页?还是我需要做一些更正?

我已经尝试添加$urlMatcherFactoryProvider.strictMode(true);,但它不起作用(不确定我是否正确,第一行变成miNgAppplication.config(['$routeProvider', '$urlMatcherFactoryProvider', function ($routeProvider, $urlMatcherFactoryProvider) {,对吗?)。

【问题讨论】:

    标签: angularjs angular-routing


    【解决方案1】:

    当没有匹配时,使用otherwise方法设置默认url。

    miNgAppplication.config(['$routeProvider', function ($routeProvider) {
        $routeProvider
            .when("/", {
                templateUrl: "Base/FirstPage",
                controller: "miNgControllerFirstPage"
            });
        $routeProvider.otherwise('/'); // <-- this should take the user to the first page.
    }]);
    

    【讨论】:

    • 这不能正常工作,我猜是因为 url 被误解了。确切的网址是http://localhost/apps/TestClient。它将其转换为 http://localhost/apps/TestClient#/otherwise 尝试重定向,但 templateUrl 不知何故添加错误。它不寻找http://localhost/apps/TestClient/Base/FirstPage,而是寻找http://localhost/apps/Base/FirstPage 在控制台中生成错误。可能当 URL 是 /apps/TestClient/#/ 时,它无法理解基础是 /apps/TestClient/,但是当它是 /apps/TestClient#/ 时,它认为基础只是 /apps/
    • 感谢您的建议。我没有找到一个简单的解决方案,我决定监听路由事件并在它以 #/ 结尾但不以 /#/ 结尾时更改 url。这是一个丑陋的解决方案,但至少它有效
    【解决方案2】:

    我没有找到可行的解决方案。我希望有人能给我一个提示,同时我解决了这个(丑陋的)方式。基本上我会监听 $route 事件并在必要时重定向。

    miNgAppplication.run(function ($rootScope) {
        $rootScope.$on("$routeChangeError", function (event, next, current) {
            if (miLib.endsWith(window.location.href, "#/") && !miLib.endsWith(window.location.href, "/#/")) {
                event.preventDefault();
                var newLink = window.location.href.substr(0, window.location.href.lastIndexOf("#/")) + "/#/";
                console.clear();
                window.location.href = newLink;
            }
        });
    });
    

    【讨论】: