0
votes

Why is not a function? I’ve read this but I cannot make it work for my project, the error is shown in the following code

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'];
})
}

And following error is thrown:

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

4
Post all the relevant code (what is this.http?, what are the imports?), and the exact and complete error message. - JB Nizet
output the actual to see if it has json() method, you might be using the latest HttpClient that doesn't need the .json() call anymore. - Bk Santiago
@JBNizet I've edited the post - Bryan Arreola
@BkSantiago if it doesn't need it, how it would be my code? Do you have a page where I can read more about it? - Bryan Arreola
HttpClient observables don't emit Response objects. They emit the body of the response, already parsed. Read the documentation: angular.io/guide/http#making-a-request-for-json-data. Everything is much simpler when you read the documentation. - JB Nizet

4 Answers

1
votes

Make sure to import Response from

import { Response } from '@angular/http';

or try to remove it from res to get rid of the error:

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

I solve it by following the next page:

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

The get() method on HttpClient makes accessing this data straightforward. For example:

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

HttpClient automatically imports json. Let’s say you are expecting to read an object of type User.

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

Without specifying a type, your response is automatically json. No need to parse it to json.

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

0
votes

I was having the same issue but solved when I removed the CORS extension in my chrome browser