我需要在 Angular 6 中转换这个不推荐使用的 get http 查询。我有错误:
JSON 不是一个函数
.这是我的代码:
search(query: string): Observable < YoutubeSearchResult > {
const params: string =[
`q=${query}`,
`key=${this.apikey}`,
`part=snippet`,
`type=video`,
`maxResult=10`
].join('&');
const queryUrl = `${this.apiurl}?${params}`;
// const queryUrl = "";
/**ritorna richiesta http get oppure con Httpclient (POST,DELETE,GET), usp map per il Response
* e estraggo l'oggetto usando.json e itero il risultato e lo converto in SearchResult
*/
return this.http.get(queryUrl).map((response: Response) => {
return (<any>response.json()).items.map(item => {
return new YoutubeSearchResult({
id: item.id.videoId,
title: item.snippet.title,
description: item.snippet.description,
thumbnailUrl: item.snippet.thumbnails.high.url
});
})
});
}
试试这个:
search(query: string): Observable<YoutubeSearchResult[]> {
const params: string = [
`q=${query}`,
`key=${this.apikey}`,
`part=snippet`,
`type=video`,
`maxResult=10`
].join('&');
const queryUrl = `${this.apiurl}?${params}`;
return this.http.get(queryUrl)
.pipe(
map(
(youTubeData: any) => {
const items = [];
console.log(youTubeData);
youTubeData.items.forEach(x => {
items.push(
new YoutubeSearchResult(
x.id.videoId,
x.snippet.title,
x.snippet.description,
x.snippet.thumbnails.high.url
)
);
});
return items;
}
)
);
这样称呼它:
findStuff() {
this.search('lazy').subscribe((searchResults: YoutubeSearchResult[]) => {
console.log('search results: ', searchResults);
});
}