2016-10-16 43 views
1

我正在使用Angular 2和Node.js,并且我正在尝试整合braintree,这并非简单的任务。如何处理来自HTTP的响应Post

我发现在没有重定向页面的情况下从事务返回结果对象的唯一解决方案是让HTTP Post请求发回对象。这可能吗?

onClick(){ 
var headers = new Headers(); 
headers.append('Content-Type', 'application/json'); 

var data = JSON.stringify({ 
    "nonce": localStorage.getItem('nonce'), 
    "amount": "5.88", 
    "firstName": this.model.firstName, 
    "lastName": this.model.lastName, 
    "customerId": this.model.userID, 
    "phoneNumber": this.model.phoneNumber, 
    "shippingStreet": this.model.shippingStreet, 
    "shippingCity": this.model.shippingCity, 
    "shippingZip": this.model.shippingZip, 
    "shippingState": this.model.shippingState, 
    "billingStreet": this.model.billingStreet, 
    "billingZip": this.model.billingZip, 
    "billingState": this.model.billingState, 
    "billingCity": this.model.billingCity, 
    "email": this.userEmail, 
    "date": this.date 
}); 

this.http.post('http://MyUrl.com:3300/checkouts', data, {headers: headers}) 
.subscribe(); 
console.log(data); 
console.log("Successfully submitted data to API server...");} 

是否需要向.subscribe()添加一些内容?我需要添加到服务器功能?

总之,我需要HTTP Post方法来发布数据并等待一个对象从接受HTTP Post方法的服务器返回,并使用初始数据创建一个对象。

此外,万一它很重要,我的服务器和前端位于不同的端口。

回答

1

如果我正确理解你的问题,你需要给.subscribe方法一个回调函数,以便做你想做的事情。回调应该采取成功和错误功能,例如):

this.http.post('http://MyUrl.com:3300/checkouts', data, {headers: headers}) 
    .subscribe(
     (response) => {console.log(response)}, 
     (error) => {console.log(error)} 
    ); 
+0

看起来这正是我正在寻找的! –