/ 当我从youtube API得到响应时,在下面的代码服务和组件中,它给了我一个403错误,它给出了一个404错误的响应,消息是 "超过了未认证使用的每日限制。继续使用需要注册。"
export class YoutubeServiceService {
constructor(
private http: HttpClient,
@Inject(YOUTUBE_API_KEY) private apiKey: string,
@Inject(YOUTUBE_API_URL) private apiUrl: string
) {}
search(query: string): Observable<SearchResult[]> {
const params: string = [
`q=${query}`,
`part=${this.apiKey}`,
`part=snippet`,
`type=video`,
`maxResults=8`,
].join('&');
const queryUrl = `${this.apiUrl}?${params}`;
return this.http.get(queryUrl).pipe(map((response) => {
return <any>response['items'].map((item) => {
console.log('raw items', item);
return new SearchResult({
id: item.id.videoId,
title: item.snippet.title,
description: item.snippet.description,
thumbnailUrl: item.snippet.thumbnailUrl.high.url,
});
});
})
);
}
}
/这是一个搜索组件,我想搜索输入框中的任何字符串来获取数据。
import
{
Component,
OnInit,
Output,
ElementRef,
EventEmitter,
} from '@angular/core';
import { SearchResult } from '../search-result.model';
import { YoutubeServiceService } from '../youtube-service/youtube-service.service';
import { Observable, fromEvent } from 'rxjs';
import { map, filter, debounceTime, switchAll ,tap} from 'rxjs/operators';
@Component({
selector: 'app-search-box',
template: `<input type="text" class="form-control" placeholder="search"
autofocus >`
})
export class SearchBoxComponent implements OnInit {
@Output() loading: EventEmitter<boolean> = new EventEmitter<boolean>();
@Output() results: EventEmitter<SearchResult[]> = new EventEmitter<
SearchResult[]
>();
constructor(private youtube: YoutubeServiceService, private el: ElementRef) {}
ngOnInit(): void {
fromEvent(this.el.nativeElement, 'keyup')
.pipe(
map((e: any) => e.target.value), //extract the value of the input
filter((text: string) => text.length > 1) ,// filter pout if empty
debounceTime(250), //only once every 250s
tap(() => this.loading.emit(true)), //enable loading
map((query: string) => this.youtube.search(query)), //search, discarding old events if new input comes in
switchAll()
)
.subscribe(
(results: SearchResult[]) => {
//on sucess
this.loading.emit(false);
this.results.emit(results);
},
(err: any) => {
//on error
console.log(err);
this.loading.emit(false);
},
() => {
// on completion
this.loading.emit(false);
}
);
}
}
在您的 search()
函数,看起来你是将你的API密钥设置为 "part "查询参数。YouTube Data API 参考资料规定,你的 API 密钥应该在 "key "查询参数中提供。
尝试设置您的 params
这样的字符串。
const params: string = [
`q=${query}`,
`key=${this.apiKey}`,
`part=snippet`,
`type=video`,
`maxResults=8`,
].join('&');
我假设 YOUTUBE_API_URL
是指向搜索端点的,你可以在 https:/developers.google.comyoutubev3docssearchlist。.