2017-07-26 94 views
0

我試圖做一個Web應用程序,我想測試HTTP功能,但我有一個問題。角4:HTTP不發送POST數據

例如:我有這樣的:

import { Injectable } from '@angular/core'; 

import { Headers, RequestOptions, Http } from '@angular/http'; 

import {Observable} from 'rxjs/Rx'; 

// Import RxJs required methods 
import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/catch'; 

@Injectable() 
export class UserService { 

    constructor(private http: Http) { } 

    create(data: Object): Observable<any> { 

     let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'}), 
       options = new RequestOptions({ headers: headers}); 

     return this.http.post('http://localhost:8000/api/signin', {headers:headers}).map((res) => { res.json(); alert('ma-ta'); }).catch((error:any) => Observable.throw(error.message)); 
    }  
} 

的函數被調用,我覈實,但http.post不工作​​,我的意思是,它不是將數據發送到該鏈接,在控制檯我什麼都沒有的網絡,我收到此:

12:01:18.779 Object { _isScalar: false, source: Object, operator: Object } 1 main.bundle.js:444:9 

這是一個有點空,唯一的東西我不需要,這樣的錯誤信息或東西。 有人能幫助我嗎?

回答

1

您正在發送一個空的帖子。您正在設置標頭(這不是必需的),而不是通過post請求發送數據。請看下面:

create(data: Object): Observable<any> { 
    let url: string = 'http://localhost:8000/api/signin';  
    return this.http.post(url, data) 
    .map((res: Response) => res.json()) 
    .catch((error:any) => Observable.throw(error.message)); 
} 

還記得導入以下:

import { Injectable } from '@angular/core'; 
import { Http, Response } from '@angular/http'; 
import { Observable } from 'rxjs/Observable'; 
import 'rxjs/Rx'; 
+0

它是一樣的,也許我進口的東西錯了嗎?我使用'@ angular/http'中的import {HttpModule}; –

+0

是你的API期望的應用程序/ json的內容類型?你確定你的「數據」正在通過嗎?你確定你的API期待與'data'相同的模型嗎? –

+0

它在Laravel中的API並期望發佈數據,無論如何,我應該在Inspect Element - > Network中查看POST方法 –