Using Typescript to set the image source from a pipe

I've been working on creating a custom pipe similar to the code below:

@Pipe({
   name: 'imagePipe'
})

@Injectable()
export class ImagePipe {
  constructor(public someService: SomeService, public storage: Storage) {
} 

  transform(value: any, arg: any) {
     if ((value != null) && (value!=arg)){
            return this.storage.get(value).then((val) => {
                            console.log('Your source is', val);

                })
    }
  }
}

The main purpose of this pipe is to look for a specific value in storage and then set the URL for an image. I'm using it like this:

<img src="{{info.title | imagePipe : otherTitle | async}}" width="45" height="120"/>

Although the console displays the correct value, unfortunately, the image URL remains null.

Answer №1

My assessment indicates two errors in this code snippet:

 if ((value != null) && (value != arg)){
    return this.storage.get(value).then((val) => {
        console.log('Your source is', val);
    });
}

Firstly, if the condition inside the if statement evaluates to false, nothing is returned. Secondly, I recommend loading storage.get into a "class var" and calling it from there for better organization.

Answer №2

The answer lies within

@Pipe({
    name: 'imageConverter'
})

@Injectable()
export class ImageConverter {
    constructor(public service: SomeService, public database: Storage) {}

    transformation(value: any, argument: any) {
        if ((value != null) && (value != argument)){
            return this.database.retrieve(value).then((result) => {
                console.log('The source you seek is', result);
                return result;
            })
        }
    }
}

Certain elements of the response were inaccurate

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

Having trouble integrating a Bootstrap-based ecommerce theme into an Angular8 project?

I have a bootstrap-based ecommerce theme with all the necessary files. The HTML theme is loading perfectly. Check out the official theme page I am integrating into my angular8 project: Theme Page Link I have created a repository for my angular8 project ...

The CORS policy has restricted access to the XMLHttpRequest from the specified origin at "http://...." to 'http://localhost:4200'

I'm currently facing a challenge while trying to make an API call, as I encountered a CORS error. When attempting with "https://....", the service failed and threw the following error: Status Code: 422. OPTIONS 422 (Unprocessable Entity) Access to ...

It can be time-consuming to render a large quantity of dynamic markers on Leaflet after receiving a response

Incorporating leaflet.js into my web project, I am faced with the challenge of creating a map view with dynamic markers. Upon receiving a response, I attempt to generate dynamic components based on the data and utilize change detection to monitor updates. ...

Discover the Hassle-Free Approach to Triggering Angular Material Menu with ViewChild and MatMenuTrigger

Is there a way to programmatically open an Angular Material menu using a Template Reference Variable on a button trigger that is accessed in the component through ViewChild? I want the menu to open when the mouse hovers over it, instead of just clicking i ...

how can I update a class of an element when the input box is disabled in angular?

Is there a way in Angular to change the class of a separate element (calendar icon button) when it detects that an input textbox is disabled? I have a disabled input type textbox and I want the class of the calendar icon button to be changed based on its d ...

Angular 2 encountered a fatal error: Issues with parsing the template:

Here is the code snippet I am currently working with: <div class="container"> <div [hidden]="loggedIn"> <md-grid-list cols="6" [style.margin-top]="'20px'"> <md-grid-tile [colspan]="1"></md-grid-tile> I have already ...

What is the process for extracting the background color from a typescript file in Angular and connecting it to my HTML document?

My typescript array population is not changing the background color of my div based on the values in the array. I've attempted to set the background using [style.backgroundColor]="statusColor[i]", where statusColor is an array declared in my typescrip ...

There will be no further upgrades available for Angular CLI after version 1.6.0

Based on the latest information from npm, the current version of @angular/cli is v6.2.5. Upon running ng -v, the output shows: _ _ ____ _ ___ / \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _| / △ &b ...

Error: The identifier HTMLVideoElement has not been declared

Encountering an issue while attempting to build my Angular 9 Universal project for SSR: /Users/my-project/dist/server.js:28676 Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__metadata"])("design:type", HTMLVideoElement) ReferenceError: HTMLVideoElem ...

The call to the hooks is not valid. Hooks must be called within the body of a functional component

Could you please take a moment to review the validate method within the elfe-if condition in the code snippet below? I am encountering an issue when trying to invoke the useLocation method from react-router-dom. Upon researching online, I came across simil ...

The missing binding.node file is causing an issue with Node-sass

Previously, my angular project 7.1 was running smoothly until I upgraded to ubuntu 19.10 and encountered an error upon running npm install: > [email protected] install /home/gabb/dev/homepage/node_modules/node-sass > node scripts/install.js Do ...

Having Trouble with Typescript Modules? Module Not Found Error Arising Due to Source Location Mismatch?

I have recently developed and released a Typescript package, serving as an SDK for my API. This was a new endeavor for me, and I heavily relied on third-party tools to assist in this process. However, upon installation from NPM, the package does not functi ...

Error: Unable to access the 'nativeElement' property because it is undefined - occurring during the ngAfterViewChecked lifecycle hook

I am facing issues with some of my karma jasmine unit tests failing after adding an ngAfterViewChecked. Despite initializing the "mySwitchEl" as shown below, the error persists. @Component({ selector: 'my-component', templateUrl: '. ...

Establish the default landing page as the home screen when launching the application

Hey, I'm running into a situation where I need to change the default page of my application upon loading. Is there a way to redirect from the home page to another page when the application loads? Thanks! ...

Ways to automatically close the external window upon logging out in Angular 12

I have successfully created an external window in my Angular application. Everything is working as expected, but I am facing an issue when trying to automatically close the external window upon user logout. Although I have written the code below and it wo ...

Issue encountered while setting up controls and AbstractControls in form development

Here is a snippet of code showing how I create and manipulate a form in Angular: this.myForm = new FormGroup({ points: new FormArray([ new FormGroup({ date: this.date, startTime: new FormControl(null, Val ...

I am attempting to store the primary array in local storage, but unfortunately, the value is not being saved within the React context API

I attempted to store the main array in local storage and retrieve it as global state, but I am facing an issue where the data is not being saved in the local storage. This file represents my context. import { createContext, useReducer, ReactNode, FC, use ...

Converting an array of objects into a dictionary using TypeScript

I'm attempting to convert an array of objects into a dictionary using TypeScript. Below is the code I have written: let data = [ {id: 1, country: 'Germany', population: 83623528}, {id: 2, country: 'Austria', population: 897555 ...

Using *ngIf directive in Angular to define and initialize variables

When working with Angular 10, I utilize the *ngIf directive to establish a variable in my HTML template. Here is an example of how I do this: <div *ngIf="function() as foo"> <p>Header</p> <div *ngFor="let x of fo ...

Evolving fashion trends

I'm looking to dynamically change the style of my HTML element based on screen size, similar to this example: <p [ngStyle]="{'color': isMobile() ? 'red' : 'blue'}">Lorem Ipsum</p> The code above triggers a m ...