【问题标题】:Property 'json' does not exist on type '{}'类型“{}”上不存在属性“json”
【发布时间】: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


【解决方案1】:

对我来说这看起来很奇怪......

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

我愿意

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

【讨论】:

  • 我已经有一段时间没有写这个问题了。我现在也绝对喜欢这个。
  • 现在因为 Response 类已被弃用,所以您能否在 HttpResponse 类的上下文中写下这个答案。仅仅更换是行不通的,所以请!
  • "Response" 只是一个接口。您可以创建自己的“MyCustomThing”接口并使用它。您仍然可以以相同的方式使用它。但请记住,如果您使用较新的“HttpClient”而不是“Http”,则不需要 .json()
  • 我参考了@Mackelito 的评论,这对 Angular 的较新版本很有帮助:当您使用“HttpClient”而不是“Http”时,不需要.json()
【解决方案2】:

您可以通过对Response 进行类型断言来消除此错误:

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

http.post() 将返回 Observable&lt;Response&gt;,而 map 将需要 Response 类型的对象。我认为这是当前 TypeScript AngularJS .d.ts 中缺少的定义。

【讨论】:

  • 这可能只是一个创可贴——但至少错误消失了。谢谢!
  • TypeScript 认为 res 是空对象类型。应该是什么类型的?
  • 一个observable - 提到了here
  • 如果是Response,您可能希望将其转换为&lt;Response&gt; 而不是&lt;any&gt;。问题是,TypeScript 不能自动假定 res 是 Response,因为 map 中的上下文不够具体
  • 首选as 断言语法......也不要称之为强制转换basarat.gitbooks.io/typescript/content/docs/types/…。不过 +1 ?
猜你喜欢
  • 2018-05-27
  • 1970-01-01
  • 1970-01-01
  • 2018-02-10
  • 2017-01-14
  • 2021-01-09
  • 2021-09-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多