2017-05-11 22 views
0

contact包含object.I要發送到http.post method.Below是我的代碼,我應該在哪裏把contact對象作爲parameter.Please給出鏈接,如果任何也涉及到http.post API。 代碼:如何發送一個對象到http.post請求?

createContacts(contact) { 
    console.log('the contact inside subscribe function',contact); 
    let headers = new Headers(); 
    headers.append('Content-Type', 'application/json'); 
    this.http.post('http://localhost:8080/contacts',{headers : headers}).subscribe(res => { 
     console.log('inside postmehtod of sub.function', res.json());//only objects 

    }); 

    } 

package.json

{ 
    "name": "contactlist", 
    "version": "0.1.0", 
    "description": "A sample Node.js app using Express 4", 
    "engines": { 
    "node": "5.9.1" 
    }, 
    "main": "server.js", 
    "scripts": { 
    "start": "node server.js" 
    }, 
    "devDependencies": { 
    "mongoose": "^4.6.2", 
    "body-parser": "^1.15.2", 
    "cors": "^2.8.0", 
    "del": "2.2.0", 
    "express": "^4.14.0", 
    "http": "0.0.0", 
    "method-override": "^2.3.6", 
    "morgan": "^1.7.0", 
    "superlogin": "^0.6.1" 
    } 
} 

回答

2

Link to http post api的要求

打字稿交API:post(url: string, body: any, options?: RequestOptionsArgs) : Observable<Response>

實施例:

createContacts(contact) { 
    let headers = new Headers(); 
    headers.append('Content-Type', 'application/json'); 
    this.http.post('http://localhost:8080/contacts', contact, {headers : headers}) 
     .subscribe(res => { 
     console.log('inside postmehtod of sub.function', res.json());//only objects 
     }) 
    } 
+0

我得到了所需的結果。你可以解釋爲什麼這不起作用。 'this.http.post(的 'http://本地主機:8080 /聯繫人',JSON.stringify(接觸),...)' 這裏我已經加入'json.stringify'爲什麼代碼不與工作這條線? – Aditya

+0

你能描述*代碼不工作嗎?它應該工作。我不能重現這一點,雖然我不使用離子。不管我在後端和/或JSON.stringify在前端使用這裏bodyParser,我總是從POST方法相同的數據在我的Node.js後端 – Tom

+0

奇怪。你使用了哪個後端?你使用哪種角度版本?請做一個混帳'克隆https://github.com/jsdevtom/so_example.git && NPM我&& NPM運行debug',然後打開控制檯看起來應該像'鉻devtools鉻鏈接:// devtools/?捆綁/ inspector.html實驗=真v8only =真WS = 127.0.0.1:9229/9b6c1f94-DDAB-45f2-a551-0d9ee78c0f98' – Tom

相關問題