【问题标题】:How to debug angular routes?如何调试角度路线?
【发布时间】:2015-09-27 18:12:12
【问题描述】:

我正在尝试构建一个简单的应用程序。

我的 index.html 文件

<!DOCTYPE html>
<html>
    <head>
        <script src="/bower_components/angular/angular.js"></script>
        <script src="/bower_components/angular-route/angular-route.js"></script>
        <script src="/js/main.js"></script>
        <script src="/js/controllers/account.js"></script>
    </head>
    <body ng-app="elara">
    wuuuu
    <div ng-view></div>

    </body>
</html>

main.js 文件

var app = angular.module('elara', [
    'ngRoute'
]);

app.config(['$routeProvider',
    function($routeProvider) {
        debugger;
        $routeProvider.
            when('/', {
                templateUrl: '/html/template/home-page.html',
                controller: 'accountController'
            }).
            otherwise({
                redirectTo: '/phones'
            });
    }]);

和我的控制器:

var app = angular.module('elara', []);
app.controller('accountController', ['$scope', '$http', function(){
    $scope.username = "";
    $scope.password = "";

    $scope.register = function(){
        $http.post(config.apiAddress + "account/login/", {username: $scope.username, password: $scope.password}).then(
            function(data){
                console.log(data);
            }, function(response){
                console.log(response);
            });
    };
}]);

请注意 main.js 文件中的调试器,但调试器并没有停止。它看起来不像执行我的 app.config 函数中的内容。当导航到/ 路由时,我的home-page.html 没有加载到ng-view

【问题讨论】:

  • 顺便说一句,您忘记了控制器的参数 $scope$http

标签: angularjs


【解决方案1】:

您可以使用$routeChangeError 事件,该事件将提供rejection 对象以及其他参数。

app.run(function ($rootScope) {
    $rootScope.$on('$routeChangeError', function (evt, current, previous, rejection) {
        console.log('Route error', rejection);
    });    
});

参考:$route docs

【讨论】:

  • 将此代码块添加到 main.js 文件的底部,但没有记录到控制台:)
  • 好吧,看来我误解了它。我从不使用ngRoute,总是使用ui-router,它的等效错误方法确实以这种方式触发。似乎在ngRoute 仅用于解决
【解决方案2】:

您可以监听 $route 服务发出的多个事件。这些事件是:

  1. $routeChangeStart
  2. $routeChangeSuccess
  3. $routeChangeError
  4. $routeUpdate

您可以在此线程中找到更多信息 - https://stackoverflow.com/a/28016993/698127

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-28
    • 1970-01-01
    • 2021-01-07
    • 2019-12-12
    • 2015-08-31
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多