Angular的$routeProvider http://localhost/thisapp/ == 正常,http://localhost/thisapp/#/ == 错误。为什么?

7

我遇到了一些(虽然不是很严重的)$routeProvider的问题。

http://localhost/thisapp/运行正常,并且完美地重定向到.otherwise()。但是一旦应用程序加载并落在“主页”网址上(http://localhost/thisapp/#/)

那么它就会出错。

如果我导航到http://localhost/thisapp$location解析为http://localhost/thisapp/#/

如果我刷新(因为你知道用户会这样做),那么代码就会出错

我尝试使用$locationProvider,但那更加令人困惑。似乎我读得越多,就越困惑,因为文档中记录的内容似乎不起作用。(如果我取消下面的$locationProvider行的注释,则不会生成任何内容)。我查看了各种教程和StackOverflow上的问题,但似乎不像应该工作那样。

以下是我的配置代码:

myApp.config(function($routeProvider, $locationProvider) {

    // commented cuz it's not working 
    // $locationProvider.html5Mode(true);

    $routeProvider
        .when('/', {
            templateUrl: 'app2/components/templates/overview.html',
            controller: 'overviewController'
        })
        .when('/all_overview', {
            templateUrl: 'app2/components/templates/overview.html',
            controller: 'overviewController'
        })
        .when('/all_procurement', {
            templateUrl: 'app2/components/templates/procurement.html',
            controller: 'procurementController'
        })
        .when('/all_social', {
            templateUrl: 'app2/components/templates/social.html',
            controller: 'socialController'
        })
        .when('/all_strengthening', {
            templateUrl: 'app2/components/templates/strengthening.html',
            controller: 'strengtheningController'
        })
        .when('/all_sales', {
            templateUrl: 'app2/components/templates/sales.html',
            controller: 'salesController'
        })

        // otherwise go to all_overview
        .otherwise({
            redirectTo: '/all_overview'
        });
});

1
你的控制台出现了错误吗?它具体是如何崩溃的? - Eugene J. Lee
1
这个问题在所有浏览器中都存在吗? - Shehryar Abbasi
1
当('/', { templateUrl: 'app2/components/templates/overview.html', controller: 'overviewController' }) - Alaksandar Jesus Gene
结果证明,我基于$location设置了一个变量,当在“/#/”后面没有信息时,它自然会抛出错误。然而,这条评论上方和下方的答案也很有帮助!我将继续改进应用程序,看看是否可以从$locationprovider获取我想要的漂亮URL,并回报情况。 - MaxRocket
除了其他事情外,它还会破坏链接,因为需要<base>标签(请参见下面的答案)。 - MaxRocket
1个回答

1
似乎默认路由行为(#)和尝试启用html5路由会导致问题。尽管您尝试了.html5Mode(true),但AngularJS的新版本具有<base href />的概念,并需要额外的步骤才能工作。

在Angular 1.3之前,我们没有这个硬性要求,因此很容易编写在根上下文中部署时正常工作但在移动到子上下文时出现问题的应用程序,因为在子上下文中,所有绝对URL都将解析为应用程序的根上下文。为了防止这种情况,请在整个应用程序中使用相对URL。

为了解释什么是相对URL,这里有一个快速示例...

<!-- wrong: -->
<a href="/userProfile">User Profile</a>


<!-- correct: -->
<a href="userProfile">User Profile</a>

所以,当你说“没有生成”(我猜是白屏?)时,请检查你的浏览器控制台,你会发现以下错误:

Uncaught Error: [$location:nobase]

有几种方法可以解决这个问题。你可以通过以下方式在你的应用程序中包含一个<base href />的概念。

$locationProvider.html5Mode({
    enabled: true
});

<html ng-app="app">
    <head>
    <base href="/">
    </head>
    ...

或者您可以忽略这个<base>标签,并使用以下配置进行修改。
$locationProvider.html5Mode({
    enabled: true,
    requireBase: false
});

更多相关信息请参见Angular文档。

错误:$location:nobase 在HTML5模式下,$location需要存在一个标签!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接