我在 angularjs 中创建了一个工厂服务,其中有一个身份验证服务。如果身份验证成功,则会生成仪表板服务所需的 token 。我能够生成 token ,但不明白如何使用它。
创建一个工厂服务来获取 token 是一个好主意,这样我就可以根据需要注入(inject) Controller 吗?
登录.html:
<div ng-app="loginFormApp" ng-controller="loginFormCtrl">
<form method="post" action="" id="login_form" class="row">
<input type="text" placeholder="Login ID" ng-model="loginId" >
<input type="password" placeholder="Password" ng-model="password" >
<input type="button" class="btn btn-theme" ng-click="loginCall()" value="Login">
<input type="button" class="btn btn-theme" ng-click="loginCall()" value="Register Here">
</form>
</div>
我的 Controller 和工厂服务(authService.js):
var app = angular.module('loginFormApp', []);
app.controller('loginFormCtrl', function ($scope, AuthService) {
$scope.loginCall = function () {
var token= AuthService.authentication($scope.loginId, $scope.password);
alert(token);
};
});
app.factory('AuthService', function ($http) {
return {
authentication: function (UserName, Password) {
$http.post("http://103.19.89.152:8080/ccp-services/authenticate", {
'userName': UserName,
'password': Password
})
.then(function (response) {
window.location.href = "http://192.168.1.144:2000/angular/dashboard.html";
var getToken = response.data.httpHeaders.h5cAuthToken;
// alert(token);
},
// Error Handling
function (response) {
console.log(response.datas);
});
}
}
});
最佳答案
此代码不起作用,因为 $http.post 返回 a promise .
var token = AuthService.authentication($scope.loginId, $scope.password);
首先,您应该返回 $http.post 方法,如下所示。
return $http.post( // rest of code
在 $http.post
之后的 then
方法中,您应该返回 token 。
.then(function (response) {
window.location.href = "http://192.168.1.144:2000/angular/dashboard.html";
return response.data.httpHeaders.h5cAuthToken; //return token
},
Controller 中的登录调用应该是
AuthService.authentication($scope.loginId, $scope.password).then(function(token) {
alert(token);
});
更新 1:重用访问 token
当然,您希望能够在身份验证调用之后在 API 调用中重用访问 token 。这可以通过执行以下操作来完成。您可以将 token “缓存”在服务本身内,而不是将访问 token 返回给调用方法。
app.factory('AuthService', function ($http) {
var cachedToken; // this is where the token will be saved after authentication
return {
authentication: function (UserName, Password) {
$http.post("http://103.19.89.152:8080/ccp-services/authenticate", {
'userName': UserName,
'password': Password
})
.then(function (response) {
window.location.href = "http://192.168.1.144:2000/angular/dashboard.html";
cachedToken = response.data.httpHeaders.h5cAuthToken; // save token to 'cache'
return cachedToken
},
function (response) { // Error Handling
console.log(response.datas);
});
},
getToken: function() { // new method to retrieve the cached token
return cachedToken;
}
}
});
在仪表板 Controller 中,您可以通过以下方式检索 token :
AuthService.getToken();
当然,您需要额外的代码来检查是否实际检索到 token (否则您将得到undefined
)。
关于javascript - 在 AngularJS 中使用工厂进行身份验证服务时 undefined object ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37880531/