【发布时间】:2016-02-28 10:22:09
【问题描述】:
我在 Typescript 中有一个抽象基类,如下所示:
import {Http, Headers, Response} from 'angular2/http';
export abstract class SomeService {
constructor(private http:Http) {}
protected post(path:string, data:Object) {
let stringifiedData = JSON.stringify(data);
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
this.http.post(`http://api.example.com/${path}`, stringifiedData, { headers })
.map(res => res.json())
.subscribe(obj => console.log(obj));
}
}
完美运行。但是,Typescript 编译器抱怨 .map(res => res.json())。我不断收到此错误:
ERROR in ./src/app/components/shared/something/some.abstract.service.ts
(13,29): error TS2339: Property 'json' does not exist on type '{}'.
我按照the angular 2 documentation 中的示例进行操作,它有效。我只是厌倦了盯着这个错误。我错过了什么吗?
【问题讨论】:
-
在我看来你已经得到的响应是 json 数据,所以 json() 调用是多余的。这是有道理的,因为您指定了接受标头,而示例链接没有。
-
@Gimby 啊 - 呃。你可能是对的,我可能会完全放弃这条线。 但是...编译器不会知道,对吧? Typescript 不应该仍然允许我这样做吗 - 因为它不知道返回数据会是什么样子?
-
坦率地说,我自己错过了 typescript 标签,对此我知之甚少:)
-
使用
.map((res: Response) => res.json())
标签: angular typescript rxjs