我正在尝试使用 Laravel 中的 api 使用 JWT 进行身份验证,当我只是在 Controller 中进行身份验证时它就可以工作,但我试图正确执行此操作并使用服务,但是我得到了一个错误。
问题是,当我在错误后刷新时,它会重定向到仪表板(在 app.js 中设置),这意味着用户已通过身份验证。
我做错了什么?为什么它给我这个错误?:
TypeError: Cannot read property 'then' of undefined
...它应该重定向到“仪表板”路线。错误位于 Controller 中的 .then(function(data)
处。
这是我的服务:
(function() {
'use strict';
angular
.module('app')
.factory('userService', ['$http', '$auth', userService]);
function userService($http, $auth) {
var service = {
userLogin: userLogin
};
return service;
function userLogin(credentials) {
$auth.login(credentials)
.then(function() {
$http.get('/api/v1/authenticate/user')
.success(function(res) {
return res;
})
.error(function(error) {
return error;
});
});
};
};
})();
这是我的 Controller :
(function() {
'use strict';
angular
.module('app')
.controller('LoginController', ['$http', '$rootScope', 'userService', LoginController]);
function LoginController($state, $rootScope, userService) {
var vm = this;
vm.login = login;
vm.error;
function login() {
var credentials = {
email: vm.email,
password: vm.password
};
userService.userLogin(credentials)
.then(function(data) {
if (data) {
var user = JSON.stringify(data.user);
localStorage.setItem('user', user);
$rootScope.currentUser = data.user;
$state.go('dashboard');
} else {
vm.error = error;
}
});
}
}
})();
最佳答案
在服务中,如果您想“then”该方法,您应该返回一个 promise 。在该服务中,userLogin 方法没有返回任何内容。
关于javascript - AngularJS:尝试使用服务,出现错误 "cannot read property ',然后是“未定义”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34193182/