Part of the DOM continuously getting refreshed in Angular 5. While trying to fetch videos from YouTube API

此生再无相见时 提交于 2019-11-30 09:49:23

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/48472550/part-of-the-dom-continuously-getting-refreshed-in-angular-5-while-trying-to-fet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!