Generating an iFrame in Angular with real-time data from Observable sources

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.

Answer №1

Could you please test this out?

Add an optional safeUrl field to the interface

export interface YoutubeData {
  videoUrl: string;
  title: string;
  description: string;
  userName: string;
  safeUrl?: string;
}

Generate a safeUrl in the observable in the following way

this.dataHubService.getYoutubeData().subscribe(data => {
    this.youtubeData = data;
    this.youtubeData.forEach(d => {
        d.safeUrl = this.domSanitizer.bypassSecurityTrustResourceUrl(d.videoUrl);
    });
});

Use safeUrl instead of videoUrl

<app-youtube-video *ngFor="let video of youtubeData;" [title]="video.title" [description]="video.description" [username]="video.userName" [videoId]="video.safeUrl">
</app-youtube-video>


<div>{{username}} presents: {{title}}</div>
<iframe [src]=safeUrl></iframe>
<div>{{description}}</div>

Please check if this solution solves the issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we eliminate the modal-open class in Angular when transitioning to a different URL?

Currently, I am facing an issue with a bootstrap modal. There is a button inside the modal which upon clicking should navigate the current component to another component named 'questions'. The problem arises when the new component is loaded, as t ...

Simple steps for Mocking an API call (Get Todos) using ComponentDidMount in React with Typescript, Jest, and Enzyme

About the application This application serves as a basic To Do List. It retrieves tasks from an API located at https://jsonplaceholder.typicode.com/todos?&_limit=5. Objective of the project The main goal is to test an API call that triggers ...

Navigating through the concept of passing objects by reference in child components of Angular 2+

Understanding that TypeScript uses object passing by reference can be challenging, especially when dealing with deep copy issues. This becomes particularly cumbersome when working within a theme. I recently encountered an issue with a component containing ...

The video on YouTube is not displaying

After spending countless hours attempting to work with the YouTube API, I am still struggling to grasp many aspects of it. My main focus is on figuring out why my video is not displaying on my jsfiddle despite copying the code exactly from another jsfiddle ...

Hiding or removing DOM elements with ng-bootstrap pagination

I am in the process of incorporating pagination into my project using ng-bootstrap pagination. In my HTML, I am combining an ngFor loop with the slice pipe to filter elements for display. <tr *ngFor="let bankAccount of bankingAccounts | slice: (p ...

What is the importance of feature modules exporting shared dependencies in AngularJS?

I've recently been diving into a tutorial about feature modules, which can be found here: . One thing that caught my attention is how the tutorial imports and then exports FormsModule in shared.module.ts. I'm curious as to why this is done. Fur ...

The type 'Observable<unknown>' cannot be assigned to type 'Observable<Something>'

I am a beginner with Angular and Firebase, facing an issue while attempting to import of from rxjs and returning null using switchMap in my auth.service.ts. import { ActivatedRoute } from '@angular/router' import { Observable, of } from 'r ...

The field list contains an unidentified column named 'Test.computerIDComputerID'

I am currently navigating through the syntax of typeORM and have been stuck troubleshooting an issue for quite some time. It appears that whenever I utilize the find() function in typeORM, a query is generated with a duplicated column from a relation. Here ...

The data type 'number' cannot be assigned to type '(...items: any[]) => number'

Currently enrolled in an online Angular course with no prior programming knowledge. I am struggling to find the solution to my coding problem. What is the mistake and where should I look for it? Not using strict mode This is my HTML code: <button c ...

Encountering build issues in my next.js application post updating to version 12.#.# and implementing Typescript

In my next.js application, I recently upgraded to version 10 and added TypeScript to the mix. Despite ironing out all issues during development, I encountered errors when running yarn next build due to my use of the keyword interface. ./src/components/ ...

Oops, it seems like there was an issue with NextJS 13 Error. The createContext functionality can only be used in Client Components. To resolve this, simply add the "use client" directive at the

**Issue: The error states that createContext only works in Client Components and suggests adding the "use client" directive at the top of the file to resolve it. Can you explain why this error is occurring? // layout.tsx import Layout from "./componen ...

The specified route type does not comply with the NextJS route requirements, resulting in an authentication error

Recently, I have encountered an issue with NextJS routes while working on an ecommerce project. I am seeking guidance to resolve this issue, specifically related to my route.ts file which interacts with NextAuth for providers like Google. During developmen ...

A guide to successfully transferring data array values from a Parent Component to a Child Component using APIs in Angular

To transfer values of this.bookingInfo = bookings.responseObj.txnValues; array from the parent component to the bookingInfo array in my child component and then insert that data into the chartNameChartTTV.data = []; array in the child component. Here, divN ...

Encountering a TypeError in Angular FormControl Jest test: Circular structure being converted to JSON issue

I encountered an error while running tests using Jest in my Angular project UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON --> starting at object with constructor 'Object' | property &apos ...

Angular can display text on hover based on the state shown in a <td> element

Working on an Angular 7 project, I have a <td> element where I display different colors to indicate the status of a task: Red - Indicates 'Delayed' Orange - Indicates 'In progress' Grey - Indicates 'Rejected' Cu ...

Can Bun automatically bundle my TypeScript files when I save them in VS Code?

Is it feasible for Bun to bundle my TypeScript upon saving a file in VS Code? The instruction manual suggests running bun run index.ts in the command line and including it in the package.json in this manner. However, I am unsure how to automate this proce ...

Error: setPosition function only accepts values of type LatLng or LatLngLiteral. The property 'lat' must be a numerical value in agm-core agm-overlay

Currently, I am utilizing Angular Maps powered by Google @agm-core and agm-overlay to implement custom markers. However, when using the (boundsChange) function on the agm-map component, an error occurs with the message "invalidValueError: setPosition: not ...

The challenges of handling dynamic controls and reactive forms in Angular when editing, and ways to effectively update their values

I am currently working on creating an inline dynamic form using reactive forms. I have successfully added a new object and looped it in the DOM, but when I press the edit button, it doesn't work and produces errors in the console. Inside the object, t ...

Group data by two fields with distinct values in MongoDB

I have developed a Typescript Node.js application and I am looking to organize documents by two fields, "one_id" and "two_id", based on a specific "one_id" value. Below is the data within my collection: { "_id":"5a8b2953007a1922f00124fd", "one_id ...

Having trouble with image loading in NextJS after replacing an old image with a new one?

I have been attempting to swap out my current banner with different images to test if they work, but every image I try leads to an error when using next/image or even a simple <image> tag. The error message states that "The requested resource isn&apo ...