Property 'json' does not exist on type '{}'

China☆狼群 提交于 2019-12-29 05:45:06

问题


I have an abstract base class in Typescript that looks like this:

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:

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?


回答1:


To me this looks strange...

.map(res => (<Response>res).json())

I would do

.map((res: Response) => res.json())



回答2:


You can get rid of this error by type-assertion to 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.



来源:https://stackoverflow.com/questions/33919710/property-json-does-not-exist-on-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!