【问题标题】:Angular res.json is not a functionAngular res.json 不是函数
【发布时间】:2018-07-05 07:38:24
【问题描述】:

为什么不是函数?我已经阅读了this,但我无法使其适用于我的项目,错误显示在以下代码中

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';

constructor(public http: HttpClient) {
}

getListVideos(listId) {
return this.http.get('https://www.googleapis.com/youtube/v3/playlistItems?key=' + this.apiKey + '&playlistId=' + listId +'&part=snippet,id&maxResults=20')
.map((res: Response) => {
  return res.json()['items'];
})
}

并抛出以下错误:

ERROR TypeError: res.json is not a function 在 MapSubscriber.project (yt.ts:18) 在 MapSubscriber._next (map.js:79) 在 MapSubscriber.Subscriber.next (Subscriber.js:89) 在 MapSubscriber._next (map.js:85) 在 MapSubscriber.Subscriber.next (Subscriber.js:89) 在 FilterSubscriber._next (filter.js:89) 在 FilterSubscriber.Subscriber.next (Subscriber.js:89) 在 MergeMapSubscriber.notifyNext (mergeMap.js:145) 在 InnerSubscriber._next (InnerSubscriber.js:23) 在 InnerSubscriber.Subscriber.next (Subscriber.js:89)

【问题讨论】:

  • 发布所有相关代码(this.http 是什么,导入是什么?),以及准确完整的错误消息。
  • 输出实际值,看看它是否有json() 方法,您可能正在使用最新的HttpClient,不再需要.json() 调用。
  • @JBNizet 我已经编辑了帖子
  • @BkSantiago 如果不需要它,我的代码将如何?你有我可以阅读更多关于它的页面吗?
  • HttpClient observables 不会发出 Response 对象。它们发出响应的主体,已经解析。阅读文档:angular.io/guide/http#making-a-request-for-json-data。阅读文档后,一切都会变得简单得多。

标签: angular ionic-framework typeerror


【解决方案1】:

我遇到了同样的问题,但在我的 chrome 浏览器中删除了 CORS 扩展后解决了

【讨论】:

    【解决方案2】:

    HttpClient 自动导入 json。假设您希望读取 User 类型的对象。

    return this.http.get<User>(url).subscribe(user => console.log(user));
    The variable user is of type User.
    

    如果不指定类型,您的响应将自动为 json。无需解析为json。

    https://angular.io/guide/http#making-a-request-for-json-data

    【讨论】:

      【解决方案3】:

      我按照下一页解决它:

      https://angular.io/guide/http#making-a-request-for-json-data

      HttpClient 上的 get() 方法使访问这些数据变得简单。例如:

       this.http.get('/api/items').subscribe(data => {
        // Read the result field from the JSON response.
        this.results = data['results'];
      });
      

      【讨论】:

        【解决方案4】:

        确保从

        导入响应
        import { Response } from '@angular/http';
        

        或尝试将其从 res 中删除以消除错误:

        .map(res => res.json()['items']);
        

        【讨论】:

          猜你喜欢
          • 2018-03-19
          • 2018-01-28
          • 2019-01-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-06-23
          相关资源
          最近更新 更多