Angular 5中不断刷新DOM的一部分.尝试从YouTube API提取视频时 [英] Part of the DOM continuously getting refreshed in Angular 5. While trying to fetch videos from YouTube API

查看:75
本文介绍了Angular 5中不断刷新DOM的一部分.尝试从YouTube API提取视频时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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>

在函数getEmbedUrl(id)中使用DOM清理器

Using DOM sanitizer in the function getEmbedUrl(id)

 getEmbedUrl(id){
      console.log(id);
    return this.sanitizer.bypassSecurityTrustResourceUrl('https://youtube.com/embed/'+id);
   }

一切正常,视频被获取,但是DOM的一部分不断刷新.我试图取消订阅所有组件生命周期挂钩.但是,如果我取消订阅,我将不会仅获取任何结果.还有其他解决方法吗,或者我在这里错过了一些东西!

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!

推荐答案

使用管道解决了问题

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做了类似的事情

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.

这篇关于Angular 5中不断刷新DOM的一部分.尝试从YouTube API提取视频时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆