I have an abstract base class in Typescript that looks like this:
我在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));
}
}
It works perfectly. However, the Typescript compiler is complaining about .map(res => res.json())
. I keep getting this error:
它完美地运作。但是,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 '{}'.
I followed the examples in the angular 2 documentation, and it works. I'm just sick of staring at this error. Am I missing something?
我按照角度2文档中的示例进行操作,它可以工作。我只是厌倦了盯着这个错误。我错过了什么吗?
2 个解决方案
#1
14
To me this looks strange...
对我来说这看起来很奇怪......
.map(res => (<Response>res).json())
I would do
我会做
.map((res: Response) => res.json())
#2
8
You can get rid of this error by type-assertion to Response
:
你可以通过类型断言来消除这个错误到Response:
.map((res: Response) => res.json())
http.post()
will return a Observable<Response>
on wich map
will require an Object of type Response
. I think that's a missing definition in the current TypeScript AngularJS .d.ts
.
http.post()将返回一个Observable
#1
14
To me this looks strange...
对我来说这看起来很奇怪......
.map(res => (<Response>res).json())
I would do
我会做
.map((res: Response) => res.json())
#2
8
You can get rid of this error by type-assertion to Response
:
你可以通过类型断言来消除这个错误到Response:
.map((res: Response) => res.json())
http.post()
will return a Observable<Response>
on wich map
will require an Object of type Response
. I think that's a missing definition in the current TypeScript AngularJS .d.ts
.
http.post()将返回一个Observable