How to implement a custom pipe for dynamically changing image URLs in Ionic 3's image tag

I am trying to set authentication headers for images called from an image tag (<img>). To achieve this, I have created a custom pipe named secureimages using the command ionic g pipe secureimages.

This pipe intercepts the HTTP requests in an interceptor where I can set the necessary header. Below is the implementation of my custom pipe:

import { Pipe, PipeTransform } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { Observable } from 'rxjs/Observable';

@Pipe({
  name: 'secureimages',
})
export class SecureImagesPipe implements PipeTransform {
  constructor(private http: HttpClient, private sanitizer: DomSanitizer) { }

    transform(url): Observable<SafeUrl> {
        return this.http
            .get(url, { responseType: 'blob' })
            .map(val => this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(val)));
    }
}

And here is how I handle the interceptor:

const headers = req.headers
  .set('Authorization', 'Bearer ' + token)
  .append('Content-Type', 'application/json');
const reqClone = req.clone({
  headers
});
return next.handle(reqClone);

To use this custom pipe in the image tag, you can do the following:

<img [attr.src]='{{this.imageURL}} | secureimages | async'/>

However, I am encountering compile errors when I try to implement this. Interestingly, using a static URL works perfectly fine. Is there a way to define dynamic image URLs in the image tag that will make use of the provided pipe?

Answer №1

Avoid using curly braces when binding attributes with square brackets [].

<img  [attr.src]=" this.imageURL | secureimages  | async "/>

Hopefully, this information is beneficial to you.

Answer №2

Identified the problem and found the solution. Following the advice of fellow contributors, I discovered that the pipes needed to be placed inside the braces. Additionally, it was necessary to initialize the dynamic image variable. In my situation, the variable had been typecasted but not properly initialized. After proper initialization, everything worked as expected. Many thanks for the help.

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

Executing npm / http-server script

I'm currently working on a shell script that will compile an Angular app using the "ng build" command and then launch a web server to host the app from the dist folder. The web server will be started with the "http-server" command, which needs to be i ...

Incorporating a specific time to a JavaScript date object

In my Angular application, I am facing an issue with adding a time to a date. The appointmentDate from the date picker returns a JavaScript date while the appointmentTime is selected from a dropdown with options like "8:00", "8:30", "9:00", etc. I'm ...

Saving JSON data retrieved from the server into an array in Angular 2

Using a nodejs server to retrieve data from an SQL database has been challenging. I attempted to store the data in taches, which is an array of Tache : getTaches(): Observable<Tache[]> { return this.http.get(this.tachesUrl) .map(response => ...

Tips for importing a PDF file and storing it in your database

I have a project using Angular 7, .NET Framework, and MongoDB where I am creating user profiles. One of the requirements is to allow users to optionally upload a PDF file along with their other information. This is what I have implemented so far: <labe ...

Unable to extend baseclass in component class in Angular 4

I am a beginner in Angular and I am attempting to extend a base class with a component class. Here is what the base class looks like: export class QuestionBase<T>{ value?: T; key?: string; label?: string; required?: boolean; order?: number ...

I am puzzled as to why my function's return type transforms into a promise when I interact with the cell.value or use console.log

Recently, I embarked on the journey of coding a validation process for my Excel Sheet. To keep the code concise, I implemented it in a straightforward manner. Here is a snippet of my source code: function main(workbook: ExcelScript.Workbook) { console. ...

How can I display an ng-container or ng-template without using *ngIf?

I am trying to incorporate the tappable directive into the ion-card component within a custom component. I am using an @Input() myInputBool, similar to this: <ng-container *ngIf="myInputBool"> <ion-card> <ng-container r ...

Creating a hybrid application with a mix of Angular and AngularJS - strategies for incorporating Angular modules into an AngularJS application

Looking to incorporate Angular components into an existing angularjs project that was created using gulp? Want to utilize downgradeModule to create a hybrid Angular/AngularJS app? Facing an issue with importing AppModule from the Angular project, as it is ...

Compatibility of Typescript with local storage

Can Typescript interact with local storage in any way? I have been setting items using the following code: localStorage.setItem('someString', JSON.stringify(MyTypescriptObject)); This method stores the object as a plain string. For example: ...

Having trouble accessing a downloaded image saved in local files from Amazon S3 using the AWS SDK in Node.js

I am currently using the node.js aws-sdk package to download files from s3 storage. However, when I download a jpeg image and save it as a local file, I am unable to view it. Is this the correct method for downloading jpeg images? public async downloadFi ...

Securing a definitive URL for a web application hosted on Azure Static Web App for long-term use

Currently, I am in the process of developing an Azure-based application. The setup I have so far consists of: The frontend being Angular v16 and hosted on an Azure Static Web Site (running on Linux) The backend utilizing an ASP.NET Core 7 Web API hosted i ...

In the realm of Typescript Angular, transferring the value of an object's property to another property within the

I'm working with a large TypeScript object and I am hoping to automate certain parts of it to streamline my workflow. myObject = [ { id: 0, price: 100, isBought: false, click: () => this.buyItem(100, 0) } buyItem (it ...

Utilize checkboxes for executing send operations and implementing prevention measures in Angular 9

I'm currently working with Angular 9 and I am facing an issue with a form that includes a checkbox. The form is designed in a way that when the user clicks the save button, it should fill in the name field. However, I have noticed that when the checkb ...

Encountered an issue in Typescript with error TS2554: Was expecting 0 arguments but received 1 when implementing useReducer and useContext in React

I've encountered several errors with my useReducers and useContext in my project. One specific error (TS2554) that I keep running into is related to the AuthReducer functionality. I'm facing the same issue with each Action dispatch. I've tri ...

Array that provides specific data types for indexes

Could be a tricky question or maybe not feasible, but I've been scratching my head over it for quite some time and just can't seem to crack it. Appreciate any help! The T generic creates a union type: const arrayToArray = <T>(values: T[]) ...

Tips on adjusting sticky behavior for responsiveness using bootstrap-4

In my project, I am utilizing angular with bootstrap. The header of the project consists of two parts and a content area. However, when the resolution is small, the header wraps. Check out the header and content on large screens View the header and conte ...

Ways to invoke main.ts to communicate with an Angular component using Electron

I have a good understanding of how to communicate between an angular app and the electron main thread using IPC. However, in my current scenario, I have threads running in the electron main thread for video processing. After these threads complete their t ...

When imported, Node / JS instantly generates a new instance

Is there a way to instantiate a class without importing it first and using new afterward? Instead of var mainClass = require('../dist/main'); // has "class Main { ... }" var mainInstance = new mainClass(); I am looking for something like var ...

Is there a way to retrieve the DOM element from an ngFor array?

Is there a way to access the actual element of an ngFor loop in order to manipulate it within the Component.ts file? Here's an example scenario: //.html <div *ngFor="let element of elements"> <md-card>{{element}} <but ...

Sorry, I can't do that task as it involves paraphrasing content that is already provided to me. How about I summarize the text instead?

I encountered an error while attempting to fetch data from an API for my Ionic 5 application. I attempted removing all the arrays but unfortunately, it did not resolve the issue. Can someone please provide assistance? Below are the files being used: type ...