无法将工厂连接到控制器

时间:2017-07-16 12:55:27

标签: javascript angularjs

我试图实施用户身份验证但不知何故我遇到了麻烦,因为它无法正常工作。我没有得到任何具体的错误,但是当我按下登录按钮时它没有做任何事情。 当我打开"网络" Chrome开发工具上的标签,我没有看到任何API调用。

这是我的authServices.js

angular.module('authServices', [])
.factory('Auth', ['$http', function ($http) {
    var authFactory = {};

    authFactory.doLogin = function (loginData) {
        return $http({
            method: 'POST',
            url: 'http://localhost:3000/api/users/authenticate',
            data: loginData
        }).then(function (data) {
            console.log(data.data.token);
            return data;
        })
    };
    return authFactory;
}]);

login.js

angular.module('logInUserCtrl', ['authServices'])
.controller('logCtrl', ['$scope', '$location', '$http', '$timeout', 
'Auth', function ($scope, $location, $http, $timeout, Auth) {

    $scope.doLogin = function (loginData) {
        $scope.loading = true;
        $scope.errorMsg = false;

        Auth.login(app.loginData)
            .then(function (data) {
                if (data.data.success) {
                    $scope.loading = false;
                    $scope.successMsg = data.data.message + 'Redirecting...';
                    $timeout(function () {
                        $location.path('/')
                    }, 2000);
                } else {
                    $scope.loading = false;
                    $scope.errorMsg = data.data.message;
                }
            })
    }
}
])

和我的login.html

 <form ng-submit="logCtrl.doLogin(loginData)">
            <label>E-Mail:</label>
            <input class="form-control" type="text" name="email" placeholder="please enter email"
                   ng-model="loginData.email">
            <br>
            <label>Username:</label>
            <input class="form-control" type="text" name="username" placeholder="please enter username"
                   ng-model="loginData.username">
            <br>
            <label>Password:</label>
            <input class="form-control" type="password" name="password" placeholder="please enter password"
                   ng-model="loginData.password">
            <br>
            <button class="btn btn-primary" type="submit" formmethod="post">Login</button>
        </form>

提前致谢!

1 个答案:

答案 0 :(得分:2)

由于您未使用 Controller as syntax ,请将按钮功能更改为,

<form ng-submit="doLogin(loginData)">

还要确保HTML中的控制器看起来像

<div ng-controller="logCtrl">