2016-10-16 89 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

看起來這正是我正在尋找的! –