Angular $ routeProvider http:// localhost/thisapp/== ok,http:// localhost/thisapp /#/ == error.为什么?

Max*_*ket 7 html javascript angularjs angularjs-ng-route

我有(虽然是次要的)问题$routeProvider.

http:// localhost/thisapp /工作正常,并重定向到.otherwise()完美.但似乎一旦应用程序加载并登陆"home"url(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'
        });
});
Run Code Online (Sandbox Code Playgroud)

scn*_*iro 1

看起来默认路由行为 ( #) 和尝试启用 html5 路由会给您带来问题。尽管您尝试这样做.html5Mode(true),但较新版本的 AngularJS 有一个 a 的概念<base href />,并且需要额外的步骤才能工作。

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

为了解释相对 URL 的含义,这里有一个简单的例子......

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


<!-- correct: -->
<a href="userProfile">User Profile</a>
Run Code Online (Sandbox Code Playgroud)

因此,当您说“没有生成任何内容”(我猜是白屏?)时,检查您的浏览器控制台,您会发现以下错误

未捕获的错误:[$location:nobase]

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

$locationProvider.html5Mode({
    enabled: true
});
Run Code Online (Sandbox Code Playgroud)
<html ng-app="app">
    <head>
    <base href="/">
    </head>
    ...
Run Code Online (Sandbox Code Playgroud)

或者您可以忽略此<base>标签并使用以下内容修改您的配置

$locationProvider.html5Mode({
    enabled: true,
    requireBase: false
});
Run Code Online (Sandbox Code Playgroud)

有关该主题的更多信息,请参阅 Angular 文档

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