我正在尝试创建一个将令牌返回给控制器的工厂。此代码仅适用于从服务器获取令牌但不将令牌传递回控制器。令牌在控制器内部空回来。请指教。谢谢。
securityApp.factory("getTokenFromServer", function ($http, $q) {
var token;
function getToken(userName, password) {
var deferred = $q.defer();
$http({
method: 'POST', url: 'http://localhost:62791/token', data: { username: userName, password: password, grant_type: 'password' }, transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}).then(function (data) {
token = data.access_token;
deferred.resolve(token);
});
return deferred.promise;
}
return {
getToken: getToken
};
});
securityApp.controller('membersController', function ($scope, $http, getTokenFromServer) {
$scope.username = 'aharris1@test.com';
$scope.password = 'SuperPass1!';
getTokenFromServer.getToken($scope.username, $scope.password).then(function (data) {
$scope.token = data;
alert($scope.token);
$http({ method: 'GET', url: '/api/Members/?access_token=' + $scope.token, headers: { 'Authorization': 'Bearer ' + $scope.token } })
.then(function (response) {
$scope.members = response.data;
});
});
});
答案 0 :(得分:1)
这是因为您没有以正确的方式访问数据。当使用承诺的then
链时,结果是数据,状态等的组合。(与成功回调相反,它会分解碎片并将数据作为第一个参数提供给你)所以我相信你应该寻找result.data.access_token
而不是result.access_token
.then(function (result) {
token = result.data.access_token;
deferred.resolve(token);
});
有了你,你可以简化你的api方法来返回http promise本身,而不是创建一个deferred对象: -
securityApp.factory("getTokenFromServer", function ($http, $q) {
function getToken(userName, password) {
return $http({
method: 'POST', url: 'http://localhost:62791/token', data: { username: userName, password: password, grant_type: 'password' }, transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}).then(function (result) {
return result.data.access_token; //Return the data
}, function(errorResponse) {
return $q.reject(errorResponse.data);//Reject or return
});
}
return {
getToken: getToken
};
});