I have successfully implemented code using Http and now I am looking to upgrade it to use the latest HttpClient.
So far, I have taken the following steps:
- In App.module.ts: imported { HttpClientModule } from "@angular/common/http";
- Added HttpClientModule to the imports array
- In the service file below (refer to code): imported { HttpClient } from "@angular/common/http";
- Replaced Http with HttpClient in the constructor by injecting HttpClient instead of Http.
However, I am struggling with the next steps (specifically how to refactor return this.http.get(queryUrl)..
)
Any suggestions or solutions?
...
Original Code using Http:
import { Injectable, Inject } from "@angular/core";
import { Http, Response } from "@angular/http";
import { Observable } from "rxjs/Observable";
import { SearchResult } from "../models/search-results.model";
export const YOUTUBE_API_KEY = "AIzaSyCIYsOjnkrIjZhVCFwqNJxe1QswhsliciQ";
export const YOUTUBE_API_URL = "https://www.googleapis.com/youtube/v3/search";
@Injectable()
export class YoutubeSearchService {
constructor(
private http: Http,
@Inject(YOUTUBE_API_KEY) private apiKey: string,
@Inject(YOUTUBE_API_URL) private apiUrl: string,
) {}
search(query: string): Observable<SearchResult[]> {
const params: string = [
`q=${query}`,
`key=${this.apiKey}`,
`part=snippet`,
`type=video`,
`maxResults=10`,
].join("&");
const queryUrl = `${this.apiUrl}?${params}`;
return this.http.get(queryUrl).map((response: Response) => {
return (<any>response.json()).items.map(item => {
// console.log("raw item", item); // uncomment if you want to debug
return new SearchResult({
id: item.id.videoId,
title: item.snippet.title,
description: item.snippet.description,
thumbnailUrl: item.snippet.thumbnails.high.url,
});
});
});
}
}
Here is the updated code