Utilizing Pipes within a Method in Angular 2 along with Dependency Injection triggers an "Insufficient Number of Arguments" error

I am searching for a solution to incorporate a custom pipe into my class. The custom pipe itself ( referenced from this source, many thanks ) involves injecting a dependency (the DomSanitizationService).

import { Pipe, Inject, Injectable } from '@angular/core';
import {DomSanitizationService, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl} from '@angular/platform-browser';

@Pipe({
    name: 'safe'
})
export class SafePipe {

    constructor( protected _sanitizer: DomSanitizationService) {  }

    public transform(value: string, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
        switch (type) {
            case 'html':
                return this._sanitizer.bypassSecurityTrustHtml(value);
            case 'style':
                return this._sanitizer.bypassSecurityTrustStyle(value);
            case 'script':
                return this._sanitizer.bypassSecurityTrustScript(value);
            case 'url':
                return this._sanitizer.bypassSecurityTrustUrl(value);
            case 'resourceUrl':
                return this._sanitizer.bypassSecurityTrustResourceUrl(value);
            default:
                throw new Error(`Unable to bypass security for invalid type: ${type}`);
        }
    }

}

I can apply this pipe in my HTML template like this:

<div [innerHtml]="myHtmlContent | safe: 'html'"></div>

However, when attempting to use the pipe within my code, such as:

getMyValue():string {
    return new SavePipe().transform(this.myHtmlContent, 'html');
    // I need to specify something here, I'm aware
}

An error is raised: Invalid number of Arguments, expected 1 argument

I understand that while calling new SavePipe(), I must provide the DomSanitizationService as an argument.

What is the best way to accomplish this? Or rather, how can I modify the Pipe to inject the DomSanitizationService as required?

Answer №1

When a class is created using new SomeClass, Angular's DI is not utilized, meaning that you must manually pass all parameters.

If you want to use the DomSanitizationService in a component where you are calling new SafePipe(), you can inject it and then simply pass the injected instance.

constructor(private sanitizer: DomSanitizationService) {}
...
someMethod() {
  new SafePipe(this.sanitizer);
}

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

Is there a way to turn off eslint's no-promise-executor-return rule?

Can the eslint rule 'no-promise-executor-return' be disabled? my .eslintrc file { "env": { "es6": true, "node": true }, "extends": [ "airbnb-base" ], "globals": { "de ...

How can Angular 2 populate forms with data retrieved from a promise in a database?

I'm currently navigating through the world of Angular and Firebase, and I’ve hit a roadblock when it comes to populating my forms with data from Firebase promises. Understanding how to work with promises versus observables is also proving to be a ch ...

Utilizing Express JS: Invoking a function within my class during routing operations

Currently, I am in the process of developing a MERN Application using Typescript. I seem to be encountering an issue with this within my class. When utilizing this code snippet: router.post("/create", user.createNewUser); It becomes impossible ...

Angular 6 - Resolving the Issue of 'Function calls are not supported in decorators' in Production Builds

Currently, I'm in the process of developing a cutting-edge Angular 6 application. However, as I was progressing with the development phase and tried to create a prod build using the following command: ng build --prod To my dismay, I encountered a pe ...

When the draw event in Leaflet's map is finished, activate the Angular Material dialog

I'm looking to activate an Angular Material dialog when the Leaflet draw's draw:drawstop event takes place. How can I ensure that Leaflet events occur within Angular's zone or how can I monitor Leaflet's changes (outside of Angular&apos ...

What is the best way to include text or a label on my Angular map without using a marker?

I am currently using the agm-map module in my angular project. I want to place a label or text at the center of a polygon on the map without using markers. How can I achieve this functionality in Typescript? I attempted to use the MapLabel Utility for thi ...

The benefits of exporting a component from one module and using it in another module

After putting in long hours trying to figure this out on my own, I've finally decided to seek help from the community. Thank you in advance for any assistance! I have a Web Projects Module that utilizes a Webpage Component. Within the Webprojects Mod ...

Creating multiple copies of a form div in Angular using Typescript

I'm attempting to replicate a form using Angular, but I keep getting the error message "Object is possibly 'null'". HTML: <div class="form-container"> <form class="example"> <mat-form-field> ...

Tips for Looping through an Object within another Object

Is there a way to retrieve values from an Object that contains another Object nested inside? I am not overly concerned about the keys, but it would be helpful if I could access them as well. Here is an example of the response: res = {data: {name: 'na ...

Error: XYZ has already been declared in a higher scope in Typescript setInterval

I've come across an interesting issue where I'm creating a handler function and trying to set the current ref to the state's value plus 1: const useTimer = () => { const [seconds, setSeconds] = useState(0); const counterRef = useRef(n ...

Troubleshooting Issue with Filtering Nested Object Array Based on Property

At the core of my data structure lies an array of orders, each containing an array of line items. These line items, in turn, are associated with their respective categories. I am currently attempting to filter the order array based on the category ID of th ...

Having trouble with importing rxjs operators

After updating the imports for rxjs operators in my project to follow the new recommended syntax, I encountered an issue with the "do" operator. While switchMap and debounceTime were updated successfully like this: import { switchMap, debounceTime } ...

When using string as a primitive type in Vue 3, what distinguishes the usage of PropType in props from not using it?

The documentation explains how Vue does runtime validation on props with defined types. To enable TypeScript to recognize these types, constructors are cast with PropType. The code example in the documentation uses success: { type: String }, whereas it c ...

Having trouble with NativeScript debugging in WebStorm - breakpoints not triggering?

I am currently using WebStorm 2017.2.5 with NativeScript 3.3.1. (Check out my package.json file here) After setting up a run/debug configuration, I placed breakpoints in the following locations: However, when running the app, it does not stop at these br ...

Tips for organizing your Typescript code in Visual Studio Code: avoid breaking parameters onto a

Currently, I am working on an Angular project using Visual Studio Code and encountering an irritating issue with the format document settings for Typescript files. It keeps breaking parameters to a new line: Here is an example of the code before formattin ...

How can you expand the class of a library object in Animate CC using Createjs?

I am currently in the process of migrating a large flash application to canvas using Typescript, and I'm facing challenges when it comes to utilizing classes to extend library objects. When working with a class library for buttons, class BtnClass { ...

In Angular, I aim to invoke the this.addDispatchToReceive method whenever the outcome is successful within each forEach iteration

How can I ensure that the values from this.stockItemDispatch are obtained in this.addDispatchToReceive(); during each iteration of a loop, instead of only getting the last stock value? The issue is that the subscribe function runs after the foreach cycle ...

Contrasting the variance between binding through the [] syntax and abstaining

There is a unique custom my-table element that has its row property bound to the host component. There are two different ways in which HTML can be inserted: <my-table [rows]="displayEntriesCount"></my-table> and alternatively: <my-table r ...

The functionality of Angular 5 reactive form valueChanges is not functioning correctly

I am currently working with a form inside a service: this.settingsForm = this.formBuilder.group({ names: this.formBuilder.array([]), globalIDs: this.formBuilder.array([]), topics: this.formBuilder.array([]), emails: thi ...

Exploring how to set dropdown menu width for Angular2 mat-select options

Currently, I am using the angular2 mat-select control and facing an issue with the width and position of its dropdown list menu. By default, it is wider and overflows the element on both sides by a few pixels. I have not found any option for adjusting the ...