2017-07-16 62 views
0

我试图实现用户身份验证,但不知何故,我遇到了麻烦,因为它不工作。我没有得到任何具体的错误,但当我按下登录按钮时,它什么都不做。 当我在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> 

谢谢!

回答

2

既然你不使用Controller as syntax,更改按钮功能,

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

也确保您在HTML样子控制器,

<div ng-controller="logCtrl"> 
+1

它的工作!非常感谢 :) – XhensB