角 - 无法设置HTTP响应类型的正确
问题描述:
我有一个服务,它暴露了一些功能的使用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'.
我怎样才能解决这个问题,这样我可以把我的响应类型是否正确?
答
试试这个:
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);
}
不遗憾的是工作。 – Chrillewoodz
尽管事实上我期望这个工作,地图是相当无用的:D –
https://plnkr.co/edit/cSJnCp8UtKv7piG1d0yi?p=preview –