【问题标题】:AngularJS $routeProvider: routing does not workAngularJS $routeProvider:路由不起作用
【发布时间】:2016-05-03 18:20:50
【问题描述】:

我创建了一个用于身份验证的登录页面。根据认证结果,重定向到不同的页面。

//controller.js

app.controller("LoginCtrl", ['$scope', '$location', 'loginFactory', function($scope, $location, loginFactory){
    $scope.authenticate = function() {
        loginFactory.login($scope.username, $scope.password)
        .then(function(response) {
            $location.path('/home');
        }, function errorCallBack(response) {
            console.log("Failed auth");
            $location.path('/login');
        });
    }
}]);

应用与路由一起定义在下面的 config.js 中。 //config.js

var app = angular.module('ristoreApp', ['ngRoute']);
app.config(function ($routeProvider, $locationProvider, $httpProvider) {
    $routeProvider
        .when('/', {
            redirectTo: '/home'
        })
        .when('/login', { 
            templateUrl: 'views/login.html', 
            controller: 'LoginCtrl' 
        })
        .when('/home', { 
            templateUrl: 'views/home.html', 
        })
        .otherwise({ 
            redirectTo: '/login' 
        });
});

文件结构:

root/
    js/ -- config.js
        -- authentication/ -- controller.js
    views/ -- home.html
           -- login.html

当我提交登录表单时,它不会重定向到“http://127.0.0.1:8081/views/login”,而是重定向到“http://127.0.0.1:8081/views/login#/login”。加上“http://127.0.0.1:8081/login”返回 404。

我在 root 下启动 node.js。从 Chrome 的“网络”选项卡中,它显示“config.js”已加载。为什么路由不起作用?

【问题讨论】:

    标签: angularjs angularjs-routing


    【解决方案1】:

    如果不想在角度路由中使用#,需要开启Html5模式。

    var app = angular.module('ristoreApp', ['ngRoute']);
    
    app.config(function ($routeProvider, $locationProvider, $httpProvider) {
        $routeProvider
            .when('/', {
                redirectTo: '/home'
            })
            .when('/login', { 
                templateUrl: 'views/login.html', 
                controller: 'LoginCtrl' 
            })
            .when('/home', { 
                templateUrl: 'views/home.html', 
            })
            .otherwise({ 
                redirectTo: '/login' 
            });
         $locationProvider.html5Mode(true);
    });
    

    如果这不起作用,您可能必须通过将其放在 head 部分来设置页面的基础。

    <base href="/">
    

    【讨论】:

    • 我在配置中添加了$locationProvider.html5Mode(true);,并在每个html中添加了&lt;base href="/"&gt;。现在它重定向到“127.0.0.1:8081/home”,但它不加载“views/home.html”。
    • 您的 app.js 或您在上面命名的文件在哪里?如果它在文件夹中,则需要更改模板 url。听起来您的模板没有正确加载,因为路径不正确。
    • 该文件是 js/ 文件夹中的 config.js。在原始帖子中查看我的文件夹结构。
    • 把你的 templateUrl 改成这样的 templateUrl:'./views/login.html'
    • 更改 templateUrl 后,“127.0.0.1:8081/login”仍为 404
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多