I am looking to integrate multiple YouTube videos into my Angular application using iframes. The video URLs are stored in a database, and I need to fetch the 3 most recent ones on each visit.
To achieve this, the "youtube" component makes a request to a service and tries to store the returned data in an Array as shown below:
youtube.component.ts
youtubeData: Array<YoutubeData>
this.dataHubService.getYoutubeData().subscribe(data => this.youtubeData = data);
The structure of the "YoutubeData" interface is defined like this:
export interface YoutubeData {
videoUrl: string;
title: string;
description: string;
userName: string;
}
An Observable of type Array is returned by the http call from the service in the following manner:
getYoutubeData(): Observable<Array<YoutubeData>>{
return this.httpClient.get<Array<YoutubeData>>('http://localhost:80/getYTdata.php');
}
In the youtube component, there is an attempt to iterate over the youtubeData Array in the template using *ngFor, passing the content of each item as inputs to a youtube-video component:
youtube.component.html
<app-youtube-video *ngFor="let video of youtubeData;" [title]="video.title" [description]="video.description" [username]="video.userName" [videoId]="video.videoUrl">
</app-youtube-video>
youtube-video.component.html (simplified)
<div>{{username}} presents: {{title}}</div>
<iframe [src]=videoUrl></iframe>
<div>{{description}}</div>
However, when attempting to load the iframe with the video URL, it raises a security issue due to being an unsafe URL. A common solution involves bypassing this security check using something like
this.domSanitizer.bypassSecurityTrustResourceUrl(videoUrl)
, but implementing this within the async context of an Observable has proven tricky.
Is there a way to transform the URL into a SafeResourceUrl within an asynchronous operation like an Observable? Additionally, is it possible to preserve a specific state of the data received through the Observable for external access? Attempts such as .pipe(tap(data => this.youtubeData = data)).subscribe()
have not been successful, resulting in an undefined URL upon retrieval.