ngResource:Angularjs - 发送带标题和请求正文的发布请求

时间:2017-04-05 18:43:20

标签: angularjs post http-headers httprequest ngresource

我正在尝试发送包含标头和请求正文的帖子请求。到目前为止,我已达到这一点:

createJob: function(jobName, jobAddress, jobContact, jobComments) {
                    var payload = {
                        name: jobName,
                        address: jobAddress,
                        contact: jobContact,
                        comments: jobComments
                    };
                    console.log(payload);
                    return $resource(route, {}, {
                       save: {
                           method: 'POST',
                           header: {'Content-Type': 'application/json'},
                           transformRequest: function(data){
                               console.log('Data in transform request is');
                               console.log(data);
                               return data; // this will go in the body request
                           }
                       }
                    });
                }

我不知道在这种情况下有效载荷放在哪里,有什么帮助吗?此外,在拨打电话时,我正在尝试执行以下操作:

createJob(this.jobName, this.jobAddress, this.jobContact, this.jobComments).
                    save().$promise.
                    then(function (response) {
                        console.log('Create job response is');
                        console.log(response);
                    }).
                    catch(function (error) {
                        console.log('Create job error is');
                        console.log(error);
                    });

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

我找到了感兴趣的人的解决方案:

createJob: function(jobName, jobAddress, jobContact, jobComments) {
            var payload = {
                name: jobName,
                address: jobAddress,
                contact: jobContact,
                comments: jobComments
            };
            console.log(payload);
            return $resource(route, {}, {
                save: {
                    method: 'POST',
                    transformRequest: function(data){
                        console.log('Data in transform request is');
                        console.log(data);
                        return angular.toJson(data); // this will go in the body request
                    }
                }
            }).save({}, payload);
        }

createJob(this.jobName, this.jobAddress, this.jobContact, this.jobComments).$promise.
            then(function (response) {
                console.log('Create job response is');
                console.log(response);
                //Refresh the page so newly created job can be seen
                window.location.reload();
            }).
            catch(function (error) {
                console.log('Create job error is');
                console.log(error);
            });