Calling Youtube API in
ngOnInit(){
var finalURL = "https://www.googleapis.com/youtube/v3/search?key="+this.api+"&channelId="+this.chanId+"&part=snippet,id&order=date&maxResults="+this.result+""
console.log(finalURL);
this.obser$ = this.http.get(finalURL).subscribe(response=>{
console.log(response);
let ytresults= response.json();
console.log(ytresults);
ytresults.items.forEach(obj => {
console.log(obj.id.videoId);
this.ytvideolist.push(obj.id.videoId);
});
console.log(this.ytvideolist);
}
trying here to make the video url sanitized
<li *ngFor= "let id of ytvideolist">
<iframe [src]="getEmbedUrl(id)" frameborder="0" allowfullscreen></iframe>
</li>
Using DOM sanitizer in the function getEmbedUrl(id)
getEmbedUrl(id){
console.log(id);
return this.sanitizer.bypassSecurityTrustResourceUrl('https://youtube.com/embed/'+id);
}
Everything is working fine videos are getting fetched but part of the DOM continuously getting refreshed. I tried to do unsubscribe at all the component lifecycle hooks. But If I unsubscribe I won't fetch any results only. Is there any other work-around or am I missing some thing here!
Solved the problem using pipe
import { Pipe, PipeTransform } from '@angular/core';
import {DomSanitizer, SafeResourceUrl} from "@angular/platform-browser";
@Pipe({
name: 'youtubeSafeUrl'
})
export class YoutubePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer){
}
transform(videoId: string): SafeResourceUrl {
return this.sanitizer.bypassSecurityTrustResourceUrl(
`https://www.youtube.com/embed/${videoId}`);
}
}
Inside html did something like this
<div *ngFor= "let videoId of ytvideolist" class="shadow1">
<iframe [src]="videoId | youtubeSafeUrl" frameborder="0" allowfullscreen></iframe>
</div>
I was guessing problem with subscription. anyhow it resolved! I hope it helps somebody.