Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...