19
votes

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?

2
It looks to me like the response you get already is json data, so the json() call is superfluous. And that would make sense since you specify the accept header, where the example link does not. - Gimby
@Gimby ah - duh. You are probably right, I can probably drop that line altogether. But... the compiler wouldn't know that, right? Shouldn't Typescript still allow me to do this - since it doesn't know what the return data will look like? - drewwyatt
Frankly, I missed the typescript tag myself, I know little to nothing about that :) - Gimby
Use .map((res: Response) => res.json()) - Eric Martinez

2 Answers

23
votes

To me this looks strange...

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

I would do

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

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.