【问题标题】:Property json does not exist on type类型上不存在属性 json
【发布时间】:2018-05-27 16:00:55
【问题描述】:

我想从我的 URL 发出一个 http 请求,但我遇到了这个错误:

“文章”类型上不存在 json

我不知道为什么..

这是我的代码:

    getAllArticles() : Observable<Articles[]>{
    return this.http.get<Articles>(this.urlAllArticles)
      .map(res => {
      return res.json().results.map(item => {
        return new Articles(
        item.id,
        item.titre);
      });
    });
  }

IArticles 界面:

    export interface IArticles {
  id: number;
  titre: string;
}

类文章:

    class Articles {
  constructor(public id: number,
              public titre: string)
  {
  }
}

建议后的结果:

    getAllArticles() : Observable<IArticles>{
    return this.http.get<any>(this.urlAllArticles)
      .map(res => {
      return res.results.map(item => {
        return new Articles(
          item.id,
          item.titre
        );
      });
    });
  }

提前感谢您的帮助

【问题讨论】:

  • 听起来您使用的是httpClient。 httpClient 假定您的响应将是 json,因此您不需要使用 .json() 进行解析。所以你的代码应该是res.results.map(...)
  • 阅读文档angular.io/guide/http
  • @Llai,没有 .json() 我也有同样的错误
  • 你能把你的Articles接口贴出来吗?通过执行this.http.get&lt;Articles&gt;,您声明res 的类型为Articles。所以听起来resultsArticles 上不存在。也许你的界面定义不正确
  • 我编辑了我的帖子

标签: json angular typescript ionic-framework


【解决方案1】:

根据我们的对话,您需要更改 map 方法以访问与您的 json 响应匹配的属性

// service.ts
getAllArticles() : Observable<Articles[]>{
    return this.http.get<GetArticlesResponse[]>(this.urlAllArticles)
        .map(res => {
            return res.map(item => {
                return new Articles(
                    item.id,
                    item.titre
                );
            });
        });
}

// used to strictly type the http return type
export interface GetArticlesResponse {
    id: number;
    titre: string;
}

【讨论】:

  • Observable 代替 Observable 是必要的?
  • @ElGecko_76 是的,因为您返回的数组是 Articles
猜你喜欢
  • 2016-02-28
  • 1970-01-01
  • 1970-01-01
  • 2018-02-10
  • 2017-01-14
  • 2021-01-09
  • 2021-09-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多