1

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!

4

1 回答 1

1

解决了使用管道的问题

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}`);
  }

}

在 html 里面做了这样的事情

<div *ngFor= "let videoId of ytvideolist" class="shadow1">
                        <iframe [src]="videoId | youtubeSafeUrl" frameborder="0" allowfullscreen></iframe>
                </div>  

我猜测订阅有问题。无论如何它解决了!我希望它可以帮助某人。

于 2018-01-29T10:51:06.737 回答