Angular res.json不是一个函数

时间:2018-01-25 23:02:48

标签: angular ionic-framework typeerror

为什么不是功能?我已阅读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'];
})
}

抛出以下错误:

  

错误TypeError:res.json不是函数      在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)

4 个答案:

答案 0 :(得分:1)

确保从

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

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

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

答案 1 :(得分:0)

我按照下一页解决了这个问题:

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

get()上的HttpClient方法可以直接访问此数据。例如:

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

答案 2 :(得分:0)

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 :(得分:0)

我遇到了同样的问题,但是当我在Chrome浏览器中删除了CORS扩展程序时,问题就解决了