【问题标题】:How to access respsone from AngularJS POST request?如何访问来自 AngularJS POST 请求的响应?
【发布时间】:2017-07-18 22:16:18
【问题描述】:

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

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 中有效。我可以使用<serviceName>.$promise.then((data) => {// access data here}) 访问使用类似服务的GET 请求的响应,但是当我使用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 请求的响应中的令牌?

【问题讨论】:

  • 你能确认第二个答案是否有效吗?

标签: angularjs post jwt


【解决方案1】:

你可以这样做

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

或者像这样

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

angular $resource documentation

【讨论】:

  • 值得注意的是,虽然我接受了这个答案,但第二个选项正是我指定的选项不起作用。第一个完美运行,但第二个抛出关于“then”属性未定义的错误
【解决方案2】:
self.User.save(self.user).then(function(response){})

应该工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多