如何从 AngularJS POST 请求访问 respsone?



我有一个用于登录我的 Web 应用程序的服务,其中包含以下代码:

angular.
module('core.user').
factory('User', ['$resource',
function($resource) {
var url = 'http://xxx.xx.xx.xxx:3000/api/authenticate'
return $resource(url, {}, {
save: {
method: 'POST',
params: {},
}
})
}
]);

此请求不是在本网站上大多数答案所引用的常用 $http.post(( 方法中提出的。

我希望访问此请求的响应,因为它带有令牌 (JWT(,我可以看到这在 Postman 中有效。我可以使用类似的服务访问 GET 请求的响应<serviceName>.$promise.then((data) => {// access data here})但是当我使用 POST 请求时,我无法使用.then()也不能.success()

以下是我尝试访问 POST 响应的方式:

angular.
module('signIn').
component('signIn', {
templateUrl: 'sign-in/sign-in.template.html',
controller: ['$resource', 'Company', 'User', '$scope', '$rootScope', '$window',
function CompanyListController($resource, Company, User, $scope, $rootScope, $window) {
// Initialize Variables //
var self = this;
self.companies = Company.query();
self.companies.$promise.then(function(data) {
var hold = data
data = [];
for (var i = 0; i < hold.length; i ++) {
if (hold[i].CompanyID) {
data.push(hold[i])
}
}
self.companies = data;
})
self.user = new User();
// Initialize Variables //
// Sign In Function //
self.signIn = function() {
if (self.user.name && self.user.password && self.companyID){
self.user.$save()
location.href = "#!/" + self.companyID
}
}
// Sign In Function //
}
]
});

如何访问我的 POST 请求响应中的令牌?

你可以这样做

self.user.$save(function(response){
//here is the response
}, function(error){
})

或者像这样

self.user.$save().$promise.then(function(response){
//here is the response
}, function(error){
})

角度$resource文档

self.User.save(self.user).then(function(response){})

应该工作