2017-08-24 58 views
1

我有一個服務,它暴露了一些功能的使用HttpClient請求,其中之一是一個post角 - 無法設置HTTP響應類型的正確

post<T>(url: string, data: any, params?: {[key: string]: any}): Observable<HttpEvent<T>> { 
    return this.http.post<T>(this.host + url, data, this.getRequestOptions(params)); 
} 

這裏最重要的是返回簽名Observable<HttpEvent<T>>

然後當我打電話的功能,我得到了兩個問題:

this.api.post<string>('/tokens', credentials).subscribe((token: string) => {}); 

的第一個問題是,我不能與<string>類型傳遞由於皮棉錯誤說:

Expected 0 type arguments but got 1 

第二個問題是,響應中的所有數據都變爲HttpEvent<T>,而不是我發送的內容,在此示例中它應該是string類型。

所以在上面的例子中我得到這個錯誤:

Argument of type '(token: string) => void' is not assignable to parameter of type '(value: HttpEvent<{}>) => void'. Types of parameters 'token' and 'value' are incompatible. Type 'HttpEvent<{}>' is not assignable to type 'string'. Type 'HttpProgressEvent' is not assignable to type 'string'.

我怎樣才能解決這個問題,這樣我可以把我的響應類型是否正確?

回答

1

試試這個:

post<T>(url: string, data: any, params?: {[key: string]: any}): Observable<T> { 
      return this.http.post<T>(this.host + url, data, this.getRequestOptions(params)).map((res: T) => res); 
     } 
+0

不遺憾的是工作。 – Chrillewoodz

+0

儘管事實上我期望這個工作,地圖是相當無用的:D –

+0

https://plnkr.co/edit/cSJnCp8UtKv7piG1d0yi?p=preview –