在Angular 6项目中,如果你想在组件级别而不是全局(根)级别使用YouTube API,你可以按照以下步骤操作:
首先,你需要在Google Cloud Console中创建一个项目并启用YouTube Data API,然后获取API密钥。
虽然你可以直接使用YouTube API的HTTP接口,但使用客户端库可以简化操作。对于Angular,你可以考虑使用angular-youtube-api
库。
npm install angular-youtube-api --save
angular-youtube-api
)如果你选择不使用第三方库,你可以手动创建一个服务来封装YouTube API的调用。
ng generate service youtube
youtube.service.ts
中添加方法来调用YouTube API:import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class YoutubeService {
private apiKey = 'YOUR_YOUTUBE_API_KEY';
private apiUrl = 'https://www.googleapis.com/youtube/v3';
constructor(private http: HttpClient) {}
searchVideos(query: string, maxResults: number = 5): Observable<any> {
const params = {
part: 'snippet',
q: query,
key: this.apiKey,
maxResults: maxResults.toString()
};
const url = `${this.apiUrl}/search?${this.toQueryString(params)}`;
return this.http.get(url);
}
private toQueryString(obj: any): string {
return Object.keys(obj)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
.join('&');
}
}
import { Component, OnInit } from '@angular/core';
import { YoutubeService } from './youtube.service';
@Component({
selector: 'app-video-search',
templateUrl: './video-search.component.html',
styleUrls: ['./video-search.component.css']
})
export class VideoSearchComponent implements OnInit {
videos: any[] = [];
constructor(private youtubeService: YoutubeService) {}
ngOnInit() {}
search(query: string) {
this.youtubeService.searchVideos(query).subscribe(response => {
this.videos = response.items;
});
}
}
angular-youtube-api
库如果你选择了angular-youtube-api
库,你可以按照以下步骤操作:
YoutubeApiService
:import { Component, OnInit } from '@angular/core';
import { YoutubeApiService } from 'angular-youtube-api';
@Component({
selector: 'app-video-search',
templateUrl: './video-search.component.html',
styleUrls: ['./video-search.component.css']
})
export class VideoSearchComponent implements OnInit {
videos: any[] = [];
constructor(private youtubeApiService: YoutubeApiService) {}
ngOnInit() {
this.youtubeApiService.apikey = 'YOUR_YOUTUBE_API_KEY';
}
search(query: string) {
this.youtubeApiService.search().list({
part: 'snippet',
q: query,
maxResults: 5
}).subscribe(response => {
this.videos = response.items;
});
}
}
确保在你的模块中导入了YoutubeApiModule
:
import { YoutubeApiModule } from 'angular-youtube-api';
@NgModule({
declarations: [
// ...
],
imports: [
// ...
YoutubeApiModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
在你的组件模板中,你可以使用*ngFor指令来遍历视频列表并显示它们。
<div *ngIf="videos.length">
<div *ngFor="let video of videos">
<h3>{{ video.snippet.title }}</h3>
<iframe [src]="getVideoUrl(video.id.videoId)" frameborder="0" allowfullscreen></iframe>
</div>
</div>
在组件类中添加一个辅助方法来生成视频的嵌入URL:
getVideoUrl(videoId: string): string {
return `https://www.youtube.com/embed/${videoId}`;
}
这样,你就可以在Angular 6组件的级别上使用YouTube API了,而不需要在根级别进行配置。记得替换YOUR_YOUTUBE_API_KEY
为你自己的API密钥。
领取专属 10元无门槛券
手把手带您无忧上云