簡體   English   中英

類型“{}”上不存在屬性“json”

[英]Property 'json' does not exist on type '{}'

我在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 '{}'.

我按照角度2文檔中的示例進行操作, 它可以工作 我只是厭倦了盯着這個錯誤。 我錯過了什么嗎?

對我來說這看起來很奇怪......

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

我會做

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

你可以通過類型斷言來消除這個錯誤到Response

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

http.post()將返回一個Observable<Response>上至極map將需要類型的對象Response 我認為這是當前TypeScript AngularJS .d.ts缺少的定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM