Receiving a conduit from the fuel supplier with only limited information on hand

I am designing a service that will utilize pipes as templates. In order to accomplish this, I require access to the registered pipes.

The final code structure should resemble the following:

@Injectable()
class MyService {
    constructor(private injector: Injector) {}

    // example usage 'myDate | date' or 'aVariable | uppercase'
    public interpolate(text: string, params: object = {}): string {
      let p: number = text.lastIndexOf('|');
      if (p > -1) {
        let args = [this.interpolate(text.substring(0, p))];
        let pipeName = text.substr(p+1).trim();
        // additional arguments retrieved from pipeName
        pipe = this.getPipe(pipeName)
        pipe.transform.apply(pipe, args);
      } else {
         // base interpolation logic
      }
    }

    private pipeInstances: any = {}
    private getPipe(pipeName) {
      if (!this.pipeInstances[pipeName]) {
        // obtaining the required pipe instance
        this.pipeInstances[pipeName] = this.injector.get(PipesContainer).get(pipeName);
      }

      return this.pipeInstances[pipeName];
    }
}

The challenge lies in accessing pipes directly from the injector. Pipes must be provided beforehand (once for directives and once for providers). Ideally, there should be a way to retrieve them from Angular's core structures (compiler, core modules, etc.) instead of defining a new list manually.

Answer №1

When it comes to Angular, there isn't a straightforward way to access a pipe in this manner. This is because pipes are primarily used internally by the compiler and aren't meant to be injected directly. If you do need to inject pipes, they should be declared as providers.

Since pipes can be injected, the proper approach would be to retrieve their instances using an injector. One way to achieve this is by creating a mapping of available pipes.

export const pipesMap = {
  some: SomePipe
}

export const pipesList = Object.values(pipesMap);

@Injectable();
export class Pipes {
  protected pipesMap = pipesMap;

  constructor(private injector: Injector) {}

  get(pipeName) {
    return this.injector.get(this.pipesMap[pipeName]);
  }
}

...
providers: [pipesList, Pipes, ...],
...

The process of populating the map can be automated by specifying an array of pipe classes and utilizing the PipeResolver to fetch their names:

import {PipeResolver} from '@angular/compiler';

const pipeResolver = new PipeResolver();

export const pipesList = [
  SomePipe
];

export const pipesMap = pipesList.reduce((pipesMap, pipeClass) => {
  const pipeName = pipeResolver.resolve(pipeClass, true).name;
  pipesMap[pipeName] = pipeClass;
  return pipesMap;
}, {});

...

Since pipes are typically instantiated by the compiler once per binding, using injector.get(...) might not be suitable for certain pipes. One example is the AsyncPipe, which is stateful and relies on the ChangeDetectorRef dependency that cannot be injected externally.

Hence, resolving this issue may vary depending on individual pipes and their requirements. Well-structured pipes often serve as thin wrappers for documented services, so it's recommended to utilize these services directly whenever possible.

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

Unable to retrieve jwt tokens transmitted from the frontend to the backend

Having just started learning Django and simplejwt, I'm facing an issue with retrieving tokens sent from our Angular frontend labeled as "app_token" and "access_token". Despite trying variations like "HTTP_APP_TOKEN" and "HTTP_ACCESS_TOKEN", as well as ...

Using Typescript in the package.json as a dependency

After initiating a React project with typescript using the command below: npx create-react-app frontend --template typescript https://i.sstatic.net/8n4O5.png I noticed that the tyepscript, @testing, and @types libraries were added to dependencies rather ...

I am seeking a method to display formatted document texts from a file located in the asset folder within an Angular HTML document as a pop-up

Text File Content -> <b>Test</b> Below is a snippet of Angular HTML I attempted: <embed src=".\assets\docs\about\BRANCH_MASTER.txt">--> <object data=".\assets\docs&bs ...

Creating a wrapper component to enhance an existing component in Vue - A step-by-step guide

Currently, I am utilizing quasar in one of my projects. The dialog component I am using is becoming redundant in multiple instances, so I am planning to create a dialog wrapper component named my-dialog. my-dialog.vue <template> <q-dialog v-bin ...

Different types of subscriptions for forkJoin observable

I am currently making two API requests with typed responses and combining them using the Observable.forkJoin method. My goal is to store each of the results in separate typed variables. var observableOrganization: Observable<Organization> = this.get ...

What could be causing the strange output from my filtered Object.values() function?

In my Vue3 component, I created a feature to showcase data using chips. The input is an Object with keys as indexes and values containing the element to be displayed. Here is the complete code documentation: <template> <div class="row" ...

Angular 7 navigation successfully updates the URL, but fails to load the corresponding component

Despite exhausting all other options, I am still facing a persistent issue: when trying to navigate to a different component, the URL changes but the destination component fails to load. Explanation: Upon entering the App, the user is directed to either ...

Modify the color of the designated Tab in the PRIMENG TabMenu - customize the style

Currently, I am utilizing the Primeng tab menu component and facing an issue. Unfortunately, I seem to be unable to identify a method to alter the color of the selected tab to a different shade. If anyone has any insights or suggestions on how to achieve ...

Tips for creating an Angular testing scenario that encompasses the use of array.find()

I need assistance in writing a test case for the following method. I have created the code snippet below but it is not helping to improve/change the code coverage. Can anyone please guide me on what I might be doing incorrectly? Component remove(item: str ...

Using the map operator in an Angular 7 application with rxjs

Despite successfully compiling my code and having everything work perfectly, I encountered an error message in my IDE (Visual Studio Code) that is preventing me from deploying my app using ng build --prod: ERROR in src/app/training/training.service.ts(6 ...

Determine the generic types of callback in TypeScript based on the argument provided

There are numerous Stack Overflow questions that share a similar title, but it seems none of them address this particular inquiry. I'm in the process of developing a wrapper for an express RequestHandler that can catch errors in asynchronous handlers ...

Can you determine the size of an unknown array in TypeScript?

Currently diving into TypeScript and tackling some TDD challenges. Within my model file, I'm working with a property named 'innovatorQuotes' that should be an array containing strings with a fixed length of 3. I'm struggling to nail dow ...

What is the best way to treat each TS file as its own independent module?

Just starting out in the world of TS and feeling like a newbie. I've noticed that in Dart, each file in a directory can run independently and you have to explicitly import objects from other files if needed. For example: file1.dart int myFunc() => ...

Tracking code execution in React, Enzyme, and Istanbul reveals uncovered functions running during tests

I have been working on testing a React component that involves 3 functions. The tests I've written for these functions pass successfully, but my code coverage report indicates only a 33% coverage. Here is the code snippet of the component: const AddW ...

How can I resolve the infinite loop issue caused by Angular Auth guard when using routing?

My current struggle lies within the authentication guard logic and routing setup. In my app-routing.module.ts file, I have defined 3 routes: const routes: Routes = [ { path: '', loadChildren: () => import('./browse/browse.mod ...

Capable of retrieving information from an API, yet unable to display it accurately within the table structure

I'm currently working with Angular version 13.2.6 and a .NET Core API. I have two components, PaymentdetailsView (parent) and PaymentDetailsForm (child). Within the PaymentDetailsForm component, there is a form that, when submitted, makes a call to ...

What is the best way to trigger an event from a child component to a parent component in

parent.component.ts public test(){ //some code..... } parent.component.html <app-child (eventfire)="test($event)"></app-child> In this scenario, the child component button is displayed within the parent component. However, there i ...

There is an issue with the typings for React.createElement that is causing errors

Is it possible to implement React.createElement with TypeScript successfully? import React from "react"; type Props = { label: string; }; const Three: React.FC<Props> = (props: Props) => { return <div>{props.label}</div&g ...

What is the best way to transform RestApi object information into an Array?

How can I transform the data fetched from PokeApi into an Array that can be used in Angular? When trying to assign it to an Array directly in HTML, it gives an error due to its Object return type. getPokemonDetail(index) { return this.http.get(`${this ...

Issues persist with the implementation of async in Angular2+

In my Angular2+ component, I created a function that outputs the results before actually running the function. This causes the desired output to appear later than expected. The function sends a variable parameter with an HTTP request to a NodeJS backend an ...