如何使用 Angularjs 显示来自 url 的 YouTube 缩略图
how to display youtube thumbnail image from url with Angularjs
我刚开始使用 angularjs,我想显示来自 YouTube 视频的 YouTube 缩略图 url ...有没有办法在人们插入时显示视频缩略图 url in input 然后点击按钮,
PLUNKER
Youtube 提供其视频的默认缩略图。
您可以使用下面的示例 URL 创建缩略图。
http://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg
在您需要从给定的 url 中搜索 ID 并像上面那样创建 url 的地方将为您提供缩略图。
控制器
app.controller('MyCtrl', ['$scope',
function($scope) {
$scope.inputs = [];
$scope.addInput = function() {
$scope.inputs.push({
field: ''
});
}
$scope.removeInput = function(index) {
$scope.inputs.splice(index, 1);
}
$scope.set2 = function($ayd) {
var thumb = getParameterByName(this.input.ayd, 'v'),
url = 'http://img.youtube.com/vi/' + thumb + '/default.jpg';
this.thumb = url
}
function getParameterByName(url, name) {
name = name.replace(/[\[]/, "\[").replace(/[\]]/, "\]");
var regex = new RegExp("[\?&]" + name + "=([^&#]*)"),
results = regex.exec(url);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
}
]);
有很多方法,可以参考from here
Here is a simple Plunker that pulls the Youtube ID from the inputted URL with a filter and then applies the image url to the image source using the Youtube provided image paths.
app.js
var app = angular.module('plunker', []);
app.filter('getVideoId', function() {
return function(input) {
// get video id
var output = input.substr(input.indexOf("=") + 1);
return output;
}
})
index.html
<body>
<div>
<input type="text" ng-model="input.url" placeholder="Youtube URL" />
<img class="ythumb" ng-src="http://img.youtube.com/vi/{{input.url | getVideoId}}/0.jpg"/>
</div>
和AngularJS
- 首先,您需要在console.google.developers中创建一个项目。
- 启用 API YouTube API V3(设置为开启)。
- 在凭据部分,创建一个 public 访问密钥。
在控制器中VideoCtrl
例如:
'use strict';
function init() {
window.initGapi(); // Calls the init function defined on the window
}
angular.module('team')
.service('googleService', ['$http', '$q', function ($http, $q) {
var deferred = $q.defer();
this.googleApiClientReady = function () {
gapi.client.setApiKey('YOUR API KEY');
gapi.client.load('youtube', 'v3', function() {
var request = gapi.client.youtube.playlistItems.list({
part: 'snippet',
playlistId: 'PLila01eYiSBjOtR8oqXkY0i5c1QS6k2Mu',
maxResults: 8
});
request.execute(function(response) {
deferred.resolve(response.result);
});
});
return deferred.promise;
};
}])
.controller('VideosCtrl', function ($scope, $window, $sce, googleService) {
$window.initGapi = function() {
$scope.$apply($scope.getChannel);
};
$scope.getChannel = function () {
googleService.googleApiClientReady().then(function (data) {
$scope.channel = data;
}, function (error) {
console.log('Failed: ' + error)
});
};
});
并且不要忘记 init
API。在 index.html
的末尾添加这一行
<script src="https://apis.google.com/js/client.js?onload=init"></script>
初学者可能会对这个答案感兴趣:
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
const YOUTUBE_API_KEY = 'abcd--z';
const YOUTUBE_API_URL = 'https://www.googleapis.com/youtube/v3/search';
class
export class VideoDetail {
id: string;
title: string;
description: string;
thumbnailUrl: string;
videoUrl: string;
constructor(obj?: any) {
this.id = obj && obj.id || null;
this.title = obj && obj.title || null;
this.description = obj && obj.description || null;
this.thumbnailUrl = obj && obj.thumbnailUrl || null;
this.videoUrl = obj && obj.videoUrl || `https://www.youtube.com/watch?v=${this.id}`;
}
}
分量
@Component({
selector: 'app-video-listing',
templateUrl: './video-listing.component.html',
styleUrls: ['./video-listing.component.scss']
})
export class VideoListingComponent implements OnInit {
constructor(private http: HttpClient) {}
ngOnInit()
{
// bpLmn-oO60E is the videoId of video
this.search("bpLmn-oO60E").subscribe((data)=>{
console.log(data);
});
}
search(query: string): Observable<VideoDetail[]> {
const params: string = [
`q=${query}`,
`key=${YOUTUBE_API_KEY}`,
`part=snippet`,
`type=video`,
`maxResults=10`
].join('&');
const queryUrl = `${YOUTUBE_API_URL}?${params}`;
return this.http.get(queryUrl).pipe(map(response => {
return response['items'].map(item => {
return new VideoDetail({
id: item.id.videoId,
title: item.snippet.title,
description: item.snippet.description,
thumbnailUrl: item.snippet.thumbnails.high.url
});
});
}));
}
}
这对我有用 :D
<video>
<source [src]="yourvideo.mp4">
</video>
我刚开始使用 angularjs,我想显示来自 YouTube 视频的 YouTube 缩略图 url ...有没有办法在人们插入时显示视频缩略图 url in input 然后点击按钮,
PLUNKER
Youtube 提供其视频的默认缩略图。
您可以使用下面的示例 URL 创建缩略图。
http://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg
在您需要从给定的 url 中搜索 ID 并像上面那样创建 url 的地方将为您提供缩略图。
控制器
app.controller('MyCtrl', ['$scope',
function($scope) {
$scope.inputs = [];
$scope.addInput = function() {
$scope.inputs.push({
field: ''
});
}
$scope.removeInput = function(index) {
$scope.inputs.splice(index, 1);
}
$scope.set2 = function($ayd) {
var thumb = getParameterByName(this.input.ayd, 'v'),
url = 'http://img.youtube.com/vi/' + thumb + '/default.jpg';
this.thumb = url
}
function getParameterByName(url, name) {
name = name.replace(/[\[]/, "\[").replace(/[\]]/, "\]");
var regex = new RegExp("[\?&]" + name + "=([^&#]*)"),
results = regex.exec(url);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
}
]);
有很多方法,可以参考from here
Here is a simple Plunker that pulls the Youtube ID from the inputted URL with a filter and then applies the image url to the image source using the Youtube provided image paths.
app.js
var app = angular.module('plunker', []);
app.filter('getVideoId', function() {
return function(input) {
// get video id
var output = input.substr(input.indexOf("=") + 1);
return output;
}
})
index.html
<body>
<div>
<input type="text" ng-model="input.url" placeholder="Youtube URL" />
<img class="ythumb" ng-src="http://img.youtube.com/vi/{{input.url | getVideoId}}/0.jpg"/>
</div>
和AngularJS
- 首先,您需要在console.google.developers中创建一个项目。
- 启用 API YouTube API V3(设置为开启)。
- 在凭据部分,创建一个 public 访问密钥。
在控制器中VideoCtrl
例如:
'use strict';
function init() {
window.initGapi(); // Calls the init function defined on the window
}
angular.module('team')
.service('googleService', ['$http', '$q', function ($http, $q) {
var deferred = $q.defer();
this.googleApiClientReady = function () {
gapi.client.setApiKey('YOUR API KEY');
gapi.client.load('youtube', 'v3', function() {
var request = gapi.client.youtube.playlistItems.list({
part: 'snippet',
playlistId: 'PLila01eYiSBjOtR8oqXkY0i5c1QS6k2Mu',
maxResults: 8
});
request.execute(function(response) {
deferred.resolve(response.result);
});
});
return deferred.promise;
};
}])
.controller('VideosCtrl', function ($scope, $window, $sce, googleService) {
$window.initGapi = function() {
$scope.$apply($scope.getChannel);
};
$scope.getChannel = function () {
googleService.googleApiClientReady().then(function (data) {
$scope.channel = data;
}, function (error) {
console.log('Failed: ' + error)
});
};
});
并且不要忘记 init
API。在 index.html
<script src="https://apis.google.com/js/client.js?onload=init"></script>
初学者可能会对这个答案感兴趣:
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
const YOUTUBE_API_KEY = 'abcd--z';
const YOUTUBE_API_URL = 'https://www.googleapis.com/youtube/v3/search';
class
export class VideoDetail {
id: string;
title: string;
description: string;
thumbnailUrl: string;
videoUrl: string;
constructor(obj?: any) {
this.id = obj && obj.id || null;
this.title = obj && obj.title || null;
this.description = obj && obj.description || null;
this.thumbnailUrl = obj && obj.thumbnailUrl || null;
this.videoUrl = obj && obj.videoUrl || `https://www.youtube.com/watch?v=${this.id}`;
}
}
分量
@Component({
selector: 'app-video-listing',
templateUrl: './video-listing.component.html',
styleUrls: ['./video-listing.component.scss']
})
export class VideoListingComponent implements OnInit {
constructor(private http: HttpClient) {}
ngOnInit()
{
// bpLmn-oO60E is the videoId of video
this.search("bpLmn-oO60E").subscribe((data)=>{
console.log(data);
});
}
search(query: string): Observable<VideoDetail[]> {
const params: string = [
`q=${query}`,
`key=${YOUTUBE_API_KEY}`,
`part=snippet`,
`type=video`,
`maxResults=10`
].join('&');
const queryUrl = `${YOUTUBE_API_URL}?${params}`;
return this.http.get(queryUrl).pipe(map(response => {
return response['items'].map(item => {
return new VideoDetail({
id: item.id.videoId,
title: item.snippet.title,
description: item.snippet.description,
thumbnailUrl: item.snippet.thumbnails.high.url
});
});
}));
}
}
这对我有用 :D
<video>
<source [src]="yourvideo.mp4">
</video>