Cách nhúng Video Youtube vào Angular?

Khi bạn làm việc với API, để xuất url Youtube video vào iframe trong project Angular, nhưng chúng sẽ gặp lỗi?

Giải pháp

Nếu bạn nhúng theo cách thông thường như thế này sẽ không gặp lỗi:

<iframe width="560" height="315" src="https://www.youtube.com/embed/1ozGKlOzEVc" frameborder="0" allowfullscreen></iframe>


Nhưng khi bạn binding từ API ra sẽ gặp lỗi, những việc cần làm như sau:

Cài đặt thư viện sau với npm:

npm i @angular/platform-browser

Thêm code sau vào constructor:


 urlSafe!: SafeResourceUrl;

  private apiURL = environment.apiUrl;
  baseUrl: string = this.apiURL;

  constructor(
    public courseService: CourseService,
    private route: ActivatedRoute,
    public sanitizer: DomSanitizer
  ) { }
  getLecture(id: string) {
    this.courseService
      .getLecture(id)
      .subscribe((data: any) => {
        console.log(data);
        this.lecture = data;
        this.lecUrl = data.urlYoutubeVideo;
        this.urlSafe= this.sanitizer.bypassSecurityTrustResourceUrl(this.lecUrl);
      });
  }

Không có nhận xét nào:

Đăng nhận xét