Develop a custom class for importing pipes in Angular 4

Currently, I am working on creating a pipe that will replace specific keywords with the correct strings. To keep this pipe well-structured, I have decided to store my keywords and strings in another file. Below is the code snippet for reference:

import { Injectable } from '@angular/core';
import { AdvEnDictionary } from './advertiser-dict/adv-en-dictionary';
import { AdvFaDictionary } from './advertiser-dict/adv-fa-dictionary';

@Injectable()
export class AdvertiserDictionary {
    constructor(
        private advEnDictionary: AdvEnDictionary['words'], 
        private advFaDictionary: AdvFaDictionary['words']
    ) {}

    getString(keyword:string, lang:string) {
         switch(lang) {
            case 'fa':
                 return this.advFaDictionary[keyword];
            break;
            case 'en':
                 return this.advEnDictionary[keyword];
            break;
            default: 
                 return this.advFaDictionary[keyword];
         }
    }
}

Here is the implementation of the pipe:

import { Pipe, PipeTransform } from '@angular/core';
import { CookieService } from 'ngx-cookie';
import { AdvertiserDictionary } from '../classes/advertiser-dictionary';
import { PublisherDictionary } from '../classes/publisher-dictionary';

@Pipe({
  name: 'translation'
})
export class TranslationPipe implements PipeTransform {
  constructor(private cookieService: CookieService,
    private advertiserDictionary: AdvertiserDictionary, 
    private publisherDictionary: PublisherDictionary, 
  ) {}

  transform(value: string, args?: any): any {
    var [prefix, keyword] = value.split("-");
    var lang = this.cookieService.get("lang");
    switch(prefix.toLowerCase()) {
      case 'pub':
        return this.publisherDictionary.getString(
          keyword.toUpperCase(),
          lang
        );
      break;
      case 'adv':
        return this.advertiserDictionary.getString(
          keyword.toUpperCase(),
          lang
        );
      break;
    }
  }

}

However, I am facing some challenges in different scenarios:

  • When I simply add the class in the pipe, I encounter a 'No provider' error for classes.
  • When I include the class in module providers, I receive an 'invalid arguments' error for the class. Additionally, I prefer not to have this class available throughout the entire app but only for use in my pipe.

Answer №1

You have the option to design a module that incorporates both AdvertiserDictionary and PublisherDictionary.

@NgModule({
  imports: [CommonModule], 
  declarations: [
    TranslationPipe  
  ],
  providers: [AdvertiserDictionary,PublisherDictionary], 
  exports:[TranslationPipe]  
})
export class TranslationModule {}

Make sure to import the TranslationModule if you intend to utilize your Pipe.

Here is an overview:

  • in imports: include all necessary modules
  • in declarations: list components and pipes
  • in providers: specify services (using @Inject)
  • in exports: declare components used outside of the module

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

The inserted button's click event does not trigger the contentEditable DIV

I have a contentEditable DIV that I manage using the directive below: <div class="msg-input-area" [class.focused]="isMsgAreaFocused" contenteditable [contenteditableModel]="msgText" (contenteditableModelChang ...

How can you merge the class attribute with the ng-class directive based on boolean values?

In my custom directive's link function, I have the following code that dynamically generates a map using d3... map.append("g") .selectAll("path") .data(topojson.feature(counties, counties.objects.counties).features) .enter() .append("path") .attr("d" ...

The "Boostrap Confirmation" plugin in JQuery fails to appear upon the second click

After changing the confirmation method from an MVC Action to an Ajax method, I noticed that the confirmation box does not appear when clicking a second time. It seems to have stopped working possibly because the page is no longer being refreshed. How can ...

Design a unique login portal separate from all other website pages

I'm a beginner with Angular and I'm currently working on creating a login page. My issue is that I want the login page to be the only component displayed initially, and once the response is 200, I want to redirect to another component. Here&apos ...

Client-side image upload problem in Next.js API routes

I've been banging my head against this bug for a couple of hours now and I just can't seem to figure out the reason behind it. The issue is with an API route I'm trying to set up in next.js where I need to modify an image and then upload it ...

vuejs mounted: Unable to assign a value to an undefined variable

When I try to run the function below upon mounted, I encounter an error: "Cannot set the property 'days' of undefined" Here is my code snippet: function getDays(date) { this.days = (new Date()).getTime() / ...

Transforming JSON data from a Javascript object into Ruby

When I send an object from Javascript to a Sinatra POST route, I use the 'stringify' method to convert the JS object to JSON. The JSON that is being sent looks like this (based on the Chrome developer tools): {"a":1,"b":2,"c":"3"}: In my Sinatr ...

During the test, an unexpected error occurred: Configuration file error! Module 'karma-remap-istanbul' not found

Whenever I run ng test, I keep encountering the following error message - what could be causing this issue? An unhandled exception occurred: Error in configuration file! Error: Module 'karma-remap-istanbul' cannot be found Below is the content ...

The loop within a loop is causing excessive lag and is on the verge of crashing the

I need help with optimizing the performance of my app that retrieves json data. The json file contains nearly one thousand words structured like this: {"THEMES":{"THEME1":["ITEM1","ITEM2","ITEM3"],"THEME2":["ITEM1",...]...}} The size of the file is aroun ...

The Jquery ajax get method is malfunctioning

I've been trying out this code but it doesn't seem to be working. Apologies for the basic question, but I'm curious to understand why it's not functioning as expected. $(document).ready(function(){ $("button").click(function(){ ...

Ways to manage your javascript variables

Here is the code snippet I am working with: var json = jQuery.parseJSON(data); console.log(json) When I run this code, the output looks like this: Object {sql: "SELECT venta.cliente_tipodoc,count(*) AS cantidad FROM venta venta", results: Array[1], ...

Issue with Div element not appearing on Azure AD B2C page customization

Utilizing PopperJS, I attempted to incorporate a popover box that appears when the user focuses on the password field within an Azure AD B2C page customization. Despite noticing the presence of the box element, it fails to display as intended. Any assistan ...

How can the data controller of a model be accessed within a directive that has been defined with "this"?

I'm struggling with accessing data using a directive, especially when I have defined my models like this: vm = this; vm.myModel = "hello"; Here is an example of my directive: function mySelectedAccount(){ return { restrict: 'A&ap ...

Align the image in the middle using JavaScript for Firebase

I am struggling to display the center of an image within a circle-shaped <img> tag with a border-radius of 50%. The issue arises when trying to display an image fetched from Firebase storage, rather than from a URL. In attempt to solve this problem, ...

Retrieve your Docusign Access Code using the typescript httpClient.post method

I am currently struggling to obtain the access token through the Docusign API. My code is producing an error in Xcode and I am unable to make it work on my native device or browser, despite successfully testing it via Postman. When attempting to run it in ...

Transform the value of Material-UI DatePicker to seconds

I am trying to figure out how to convert the value from a React Material-Ui datepicker, which currently looks like this: 2021-05-26T01:30, into seconds. Any suggestions on how I can achieve this? PS: My goal is to create a schedule SMS module. Therefore, ...

The parameter 'host: string | undefined; user: string | undefined' does not match the expected type 'string | ConnectionConfig' and cannot be assigned

My attempt to establish a connection to an AWS MySQL database looks like this: const config = { host: process.env.RDS_HOSTNAME, user: process.env.RDS_USERNAME, password: process.env.RDS_PASSWORD, port: 3306, database: process.env.RDS_DB_NAME, } ...

Internet Explorer experiencing issues with window resizing event

One common issue with Internet Explorer is that the window.resize event is triggered whenever any element on the page is resized. It doesn't matter how the element's size changes, whether it's through height or style attribute modification, ...

Styling elements conditionally with AngularJS-controlled CSS

Looking for some guidance in Angular as a newcomer. I am attempting to adjust a style when clicked. On my page, I have multiple content spaces created using the same template. Upon clicking a "more" link, I desire to expand that specific section. I have ac ...

What is the best way to convert Arabic language HTML into a PDF document on the client side?

Utilizing jsPDF and vue js, I successfully implemented a feature to export PDFs. However, I encountered an issue with Arabic characters not displaying properly. Can anyone provide assistance in resolving this problem? ...