javascript - 路由更改后服务中的 AngularJS 函数抛出 'not a function error'?

标签 javascript angularjs node.js

我在使用 AngularJS 时遇到问题,其中我的一项服务 (authService.isLoggedIn()) 中的一个函数在我的控制台中抛出“不是函数”异常。但它仅在发生路线更改后(例如登录后)发生,因此在发生路线更改之前,从我的 $routeChangeStart 事件处理程序中成功调用该函数,但在发生路线更改后,我在我的 $routeChangeStart 事件处理程序中收到此异常控制台:

TypeError: authService.isLoggedIn is not a function
    at app.config.js:13

如果我需要发布我的服务器端代码(用于 API 路由的 NodeJS + Express),请告诉我。

这是我的index.html

<!DOCTYPE html>

<html ng-app="myApp">
<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
    <link href="stylesheet.css" rel="stylesheet">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular-route.min.js"></script>
    <base href="/">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.9/ngStorage.js"></script>
    <script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>

</head>
<body>

    <div ng-controller="navCtrl">

        <nav class="navbar navbar-default">
            <div class="container-fluid">
                <div class="navbar-header">
                    <a class="navbar-brand" href="#">TriviaAttack!</a>
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav navbar-right">
                        <li><a ng-click="showLogin()">Login</a></li>
                        <li><a ng-click="showRegister()">Register</a></li>
                    </ul>
                </div>
            </div>
        </nav>

        <div ng-view></div>

    </div>

    <script src="./js/ui-bootstrap-custom-tpls-0.14.0.min.js"></script>

    <script src="./app/app.js"></script>
    <script src="./app/app.routes.js"></script>
    <script src="./app/app.config.js"></script>
    <script src="./app/services/authInterceptor.js"></script>
    <script src="./app/services/auth.js"></script>
    <script src="./app/services/authToken.js"></script>
    <script src="./app/services/user.js"></script>
    <script src="./app/controllers/nav.js"></script>
    <script src="./app/controllers/home.js"></script>
    <script src="./app/controllers/login.js"></script>
    <script src="./app/controllers/landingpage.js"></script>

</body>
</html>

app.js

var myApp = angular.module('myApp', ['ngRoute', 'ui.bootstrap']);
console.log('myApp loaded');

app.routes.js

angular.module('myApp')
.config(function($routeProvider) {
    $routeProvider
    .when('/', {
        templateUrl: './app/views/landingpage.html',
        controller: 'landingpageCtrl'
    })
    .when('/home', {
        templateUrl: './app/views/home.html',
        controller: 'homeCtrl'
    });
});
console.log('app.route loaded');

app.config.js

angular.module('myApp')
.config(function($locationProvider, $httpProvider) {

    //Removes # from urls.
    $locationProvider.html5Mode(true);

    //Add authentication interceptor to $httpProvider.interceptors array.
    $httpProvider.interceptors.push('authInterceptor');
})
.run(function($rootScope, authService, $location) {
    $rootScope.$on('$routeChangeStart', function(event) {

        authService.isLoggedIn()
        .then(function(response) {
            console.log(response);
            if (response.status == 200) {
                $rootScope.user = response.data;
            } else {
                console.log('User not authenticated/logged in.');
            }
        });

    });
});

服务/authInterceptor.js

angular.module('myApp').
service('authInterceptor', function($location, authToken) {
    var service = this;

    service.request = function(config) {
        config.headers.authorization = authToken.getToken();
        return config;
    }


    service.responseError = function(response) {
        $location.path('/');
        return response;
    }

});

服务/auth.js

angular.module('myApp')
.service('authService', function($http) {
    var service = this;

    service.login = function(user, pass) {
        return $http.post('/api/login', {username: user, password: pass});
    }

    service.isLoggedIn = function() {
        return $http.get('/api/user');
    }

});

Controller /login.js

angular.module('myApp')
.controller('loginCtrl', function($scope, $modalInstance, $location, authService, authToken) {
    $scope.msg = '';
    $scope.loginData = {
        username: '',
        password: ''
    }
    $scope.login = function() {
        authService.login($scope.loginData.username, $scope.loginData.password)
        .then(function(response) {
            if (response.data.success) {
                authToken.setToken(response.data.token);
                authService.isLoggedIn = true;
                $modalInstance.close();
                $location.path('/home');
            } else {
                $scope.msg = response.data.message;
                console.log('error logging in');
            }
        });
        $scope.loginData = {};
    };

});

最佳答案

在你的controllers/login.js中

您正在设置

authServer.isLoggedIn to true

这使它成为“ bool 值”,对吗?

关于javascript - 路由更改后服务中的 AngularJS 函数抛出 'not a function error'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33144841/

相关文章:

jquery - Socket.io 函数仅工作一次,然后停止

javascript - 使用 JQuery 突出显示多个 Div 并保存模式

javascript - 这些格式中使用 'event' 作为参数有什么区别?

javascript - 为什么 angularjs 无法正确解析我的对象?

javascript - ng-tags-input 无法从自动完成中选择选项

angularjs - Angular UI路由器: How to go to the same state with different $stateParam?

javascript - 在 Node.js 中从连续 jpg 制作 mp4

html - 谷歌地图重叠到下面的 div 上

javascript - 如何导出 Codepen 以在网站的 HTML 中使用

javascript - 用 JS 引用对象窗口的元素 id