"Develop a unique Angular 12 custom pipe that retrieves data through a service and converts it into a string instead of

Hello Everyone, I've encountered a problem that I need help with.

import { Pipe, PipeTransform } from '@angular/core';
import { PrintingTypesService } from 'src/app/settings/services/printing-types/printing-types.service';
import { PrintingTypesModel } from 'src/app/settings/share/printing-types.model';

@Pipe({
  name: 'printingTypesPipe',
})
export class CustomPrintingTypesPipe implements PipeTransform {
  public printingTypesData: PrintingTypesModel[] = [];
  name: any;
  constructor(private printingTypesService: PrintingTypesService) {}

  transform(value: string): any {
    this.printingTypesService.fetchPrintingTypes().subscribe((data) => {
      this.printingTypesData = data;
      const selectedType = this.printingTypesData.find((o: any) => {
        return Number(o.printing_type_id) === Number(value);
      });
      this.name = '';
      this.name = selectedType!.name_e;
    });
      return this.name;
  }
}

Even though I console log the value of this.name, it doesn't display in the browser!

I've tried troubleshooting but can't pinpoint the exact issue. Any help would be greatly appreciated. Thank you!

Answer №1

Update your transform function to return an observable in the following way:

  transform(value: string): any {
    return this.printingTypesService.fetchPrintingTypes().pipe(map(data) => {
      this.printingTypesData = data;
      const result = this.printingTypesData.find((o: any) => {
        return Number(o.printing_type_id) === Number(value);
      });          
      return result!.name_e;
    });
  }

In your HTML template, make sure to use the async pipe after the printingTypesPipe.pipe method. For example:

{{ 'example' | printingTypesPipe | async }}

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

When implementing Swiper in TypeScript, an error is encountered: TypeError - Attempting to invoke the Swiper class constructor without using the 'new' keyword

I am facing an issue for which I couldn't find a solution, so I'm attempting to solve it myself for the first time. I am using TypeScript and Next.js, but unfortunately, Swiper does not offer direct support for Next.js and TS. Below is the TypeS ...

unable to transform this string into an object

https://i.sstatic.net/O46IL.pngWhy am I encountering difficulties converting this string into an object? Any assistance on resolving this error would be greatly appreciated. onSignup(data:any){ localStorage.setItem('users',JSON.string ...

Eliminate repeating elements in an array of objects with multiple levels

I'm facing a challenge with filtering an array of objects based on the condition that myDatas.items.flaggedItem should not be null, while also eliminating duplicates where myDatas.items.id are identical. This scenario should result in only 2 items bei ...

What are the distinctions between using getStaticPaths + getStaticProps and useRouter in NextJS?

I'm currently diving into the world of NextJS and finding myself puzzled by the distinctions between getStaticProps & getStaticPaths compared to utilizing useRouter().query. At this point, it appears to me that both methods serve a similar purpos ...

Having trouble triggering a dot MVC controller action method from an Angular service

Encountering the following Error: CORS policy block: Preflight request response access control check fails with HTTP ok status missing. Note: The ajax call successfully triggers the action method in other web applications, but an error is raised when usin ...

What is the best method to completely uninstall Apollo-Angular along with all of its dependencies?

Once I added apollo-angular and @apollo/client to my project, I quickly realized that I no longer needed them. However, simply using "npm uninstall apollo-angular" and "npm uninstall @apollo/client" only removed the main folders but left behind other Apoll ...

What type of observations can you make?

What is the correct way to specify the return type in the function getAll() instead of using any? getAll(): Observable<any> { return this.http .get<{ results: CharacterData[]; info: CharacterInfo; }>(characterUrl) .pipe(map((el) ...

"Creating a Typescript function that guarantees a non-null and non-undefined return

Currently, I am working on developing a function that is designed to return a specific value. In the event that the returned value is null or undefined, the function should then default to a pre-determined value. function test<A, B>(input: A, fallba ...

React Query mutation encountered a TS2554 error: Type argument was not valid

I'm a beginner when it comes to TypeScript and I am using react-query. I tried using mutate, but it is causing an error. TS2554: Expected 1-2 arguments, but got 3. interface: interface ChangePassword{ email: string; password: string; conf ...

When using Angular, a service can be declared in the viewProviders of the parent component and then accessed in the viewProviders of the child

Imagine a scenario where there is a parent component called AppComponent, a directive named MyDirective, and a service named SimpleService. In this case, MyDirective is utilized in the template of AppComponent and injects SimpleService using the Host deco ...

What are some best practices for integrating ES2020 into an Angular project?

Below is the content of my tsconfig.json file: { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "sourceMap&q ...

Accessing dynamically generated text from an li element in Angular by transferring it from the HTML to the TypeScript component

Can you assist me with this issue? Below is the code snippet: Xpressions Total ={{response.total}} clear </div> <div class="exResult"> <ul> <li *ngFor='let item of response.data'> {{item.ph ...

What is the best way to extract values from a custom type in TypeScript?

Currently, I am collaborating on a project using Angular and Django. The data is being sent from Django to Angular using GraphQL. In Angular, I have created a custom type called "TopicType" where I successfully captured the data. However, I encountered an ...

Obtain an Angular2/4 Carousel component through a service in order to create a seamless loop

I am currently working on implementing a carousel in Angular. While it is not complicated to include slide images directly in the html, I am interested in fetching them from an array stored in a service for more dynamic functionality. Here is a snippet of ...

The dropdown feature in Bootstrap 5 seems to be malfunctioning in Angular 12

I am facing issues while trying to implement the Bootstrap 5 dropdown in Angular 12. After installing all required packages and adding them to the angular.json file, I still cannot get it to work properly. Even after copying the example directly from the ...

Tips for creating a test to choose a movie from the MuiAutocomplete-root interface

I am currently utilizing Material UI with React using Typescript and I am looking to create a test for the autocomplete functionality using Cypress. Here is the approach I have taken: Identifying the Autocomplete component and opening it, Choosing an opti ...

Testing Angular 7 components: A guide to validating input element values

Upon updating an operational application from Angular 4 to Angular 7, I encountered a discrepancy. Consider the HTML Input below: <input id="encryptedValue" readonly class="form-control" [ngModel]="Response.encryptedText" size="50" /> Prior to the ...

Angular - Show a table of items from a given list

I recently started using Angular and I'm facing a challenge in displaying multiple tables based on a list of values. Each rule refNo should have its own separate rule conditions table displayed sequentially. Currently, all the tables are showing the s ...

Transform an Angular 2 application to seamlessly incorporate an SDK

I have been working on an Angular 2 application and I am curious if it is feasible to transform this into an SDK that can be easily integrated into other applications by simply adding script tags in their headers. If this conversion is not achievable, co ...

Issue when calling .create() method on Mongoose schema: "this expression is not callable" error in TypeScript

Encountering an error with the .create method on a mongoose model in Next JS while making a call in an API route. The get request is functioning properly... The structure: pages>API>task.tsx import dbConnect from "../../util/dbconnect"; im ...