Attempting to search for an item by its id within a local json file using Angular

I have a local JSON file containing Kitchen types. I created the KitchenTypesService with two functions inside, GET and FIND(ID). The GET function is working fine, but the FIND function is not working and displaying an error "ERROR TypeError: Unable to lift unknown Observable type." I am trying to use the FIND function to retrieve a kitchen with a specific ID. Can you help me identify the problem?

Service

export class KitchenTypesService {
  private _jsonURL = 'assets/data/kitchenTypes.json';
  constructor(private http: HttpClient) {
    this.get().subscribe((data) => data);
  }

  public get(): Observable<any> {
    return this.http.get(this._jsonURL);
  }

  public find(id: number) {
    this.get().subscribe(find((data: any) => data.id == id));
  }
}

Component

export class KitchenDimensionComponent implements OnInit {
  title: string = 'Virtuvės matmenys';
  step: number = 2;
  selectedKitchenId: number;
  kitchen: any;
  constructor(
    private persistenceService: PersistenceService,
    private httpKitchenTypes: KitchenTypesService
  ) {}

  ngOnInit(): void {
    this.initialSelectedKitchenId();
    console.log(this.httpKitchenTypes.find(1));
  }

  initialSelectedKitchenId(): void {
    this.selectedKitchenId = this.persistenceService.get('selectedKitchenId');
  }
}

Local KitcehTypes.json

[
  {
    "id": 1,
    "title": "Standartine",
    "src": "/assets/images/kitchen-types/one-well.png",
  },

  {
    "id": 2,
    "title": "L forma",
    "src": "/assets/images/kitchen-types/L-shaped.png",
  },

  {
    "id": 3,
    "title"": "U forma"quot;,
    "src": "/assets/images/kitchen-types/U-shaped.png",
  },

  {
    "id"": 4,
    "title": "G forma",quot;,
    "src": "/assets/images/kitchen-types/G-shaped.png",
  }
]

Error Message

[

Answer №1

If you're facing issues with HttpClient causing errors, there are ways to overcome them. While it may seem like a roadblock, there is a solution that can help you navigate through.

One approach is to directly import the JSON file with the help of resolveJsonModule. To make this work, you'll have to include the following configuration in your tsconfig.json file:

"resolveJsonModule": true

After setting this up, you can effortlessly import your data by adding the following code snippet in your service:

import * as data from './kitchenTypes.json'

Keep in mind that you might need to adjust the file path accordingly

Upon completing these steps, you will be able to access the contents of the JSON file. This enables you to view and search for specific information within the JSON file as per your requirements.

data: any = (data as any).default;

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

Enhancing Application Performance Through Next.js Development

I'm currently working on an application using next.js and I am looking to implement code splitting in order to reduce the bundle size and load pages on demand. Unfortunately, I have not been able to find a way to do this without specifying routes. Fo ...

Leveraging Angular 6: Implementing custom scripts on a component basis and verifying their presence

I need some help with a script that I want to run on a specific component only. I've managed to add the script to the component, but there are a few issues that I'm unsure how to fix. When I go to the component, the script is added to the DOM b ...

Checking if a JSON key contains a particular value in Wiremock

Looking at the request URL provided below: http://localhost:9082/v1/action/query I also have a set of requests defined in a wiremock request file: {"queryString":"Select firstname, lastname, workphone, id, accountId from mydetails} { &qu ...

Having difficulty testing an Angular/NGXS action that triggers after an unsuccessful API request

Struggling with writing tests for an NGXS action that calls an http request? Want to add tests for both successful and failed requests? Here is the code for my Action: @Action(SearchChuckNorrisJokes) searchChuckNorrisJokes({ getState, setState }: StateCo ...

Using Typescript with React functional components: the proper way to invoke a child method from a parent function

My current setup is quite simple: <Page> <Modal> <Form /> </Modal> </Page> All components mentioned are functional components. Within <Modal />, there is a close function defined like this: const close = () => ...

Place information from an input field into a specific row within a table

Utilizing Angular 4, I am developing a frontend application for a specific project. The interface features a table with three rows that need to be filled with data from an external source. https://i.stack.imgur.com/Dg576.png Upon clicking the "aggiungi p ...

I am facing a problem with the code for my React login page and router

My form page is built in react and typescript, utilizing JWT tokens on the API side. While there are no issues with the container page, I encountered an error on the index.tsx page where the routers are defined: A TypeScript error occurred in C:/Users/yusu ...

Ways to leverage a single observable to modify a second one

I'm facing an issue while trying to utilize an observable favourites$ in order to construct another array of the same type. I am anticipating that the favourites$ observable will be filled with an array of type University, and then I can update a clas ...

ngFor is failing to show the array data, which is being fetched from Firebase

Hi there, I understand that this question has been asked frequently, but the regular solutions are not working for me. ts handleChangeFormType(formType) { this.serverData.getData('questionnaire/' + formType) .subscribe( (response: Respons ...

TypeScript utility function that retrieves properties from an interface based on a specified type

Is there a way to create a new object type that includes only properties from another Object that match specific types, as opposed to property names? For example: interface A { a: string; b: number; c: string[]; d: { [key: string]: never }; } int ...

Customizing HttpErrorResponse object properties in Angular

I am new to working with Angular (8) and have been developing a frontend SPA that interacts with a Node Express backend API through http calls using the HttpClient module. In the API response, I can define an Http response status along with an additional J ...

The mat-menu generated with ngFor fails to activate the click function

I'm encountering difficulties when implementing a mat-menu using *ngfor I have consulted this response How can I utilize *ngFor with mat-menu and mat-menu-item? and although I believe I am following the same approach, I am still experiencing errors. ...

Complication with AOT compilation in ap-angular2-fullcalendar causing errors

I'm encountering a problem while trying to do AOT for my Angular 4 application, specifically when referencing ap-angular2-fullcalendar. Below are the configurations in my rollup-config.js file: ** import rollup from 'rollup'; import ...

Navigating a relative path import to the correct `@types` in Typescript

When the browser runs, I require import * as d3 from '../lib/d3.js'; for d3 to be fetched correctly. I have confirmed that this does work as intended. However, the file that contains the above code, let's call it main.js, is generated from ...

Select the implied type from a resolved Promise type in Typescript

I am working with a function called getStaticProps in Next.js that returns a Promise, resolving to an Object with the following structure: type StaticProps<P> = { props: P; revalidate?: number | boolean; } To generically "unwrap" the type o ...

Unable to display the final JSON element using C#

Recently, I embarked on learning JSON and encountered an issue in my initial simple application. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Script.Serialization; usi ...

Output Scalable Vector Graphics (SVG) content on a webpage

I need to include an SVG element in my Angular 2+ code. My goal is to provide users with the option to print the SVG element as it appears on the screen. <div class="floor-plan" id="printSectionId2" (drop)="onDrop($event)" (dragover)="onDragOver ...

"Transmitting data via HTTP POST on an Android device

While there have been previous inquiries on this topic, many of the methods mentioned are no longer relevant. I have discovered a new solution: new Thread( new Runnable() { @Override public void run() { try { St ...

One parent contains two identical components, but the first component takes precedence over the second

Within my component, I have two subcomponents that are identical: <!-- Some code ... --> <app-upload-button #idBook [accept]="'image/*'" (loadend)="onImageLoaded('#this-idbook-preview')" > </app-upload-button> ...

Scrapy generates faulty JSON output

I have implemented the following parsing method: def parse(self, response): hxs = HtmlXPathSelector(response) titles = hxs.select("//tr/td") items = [] for titles in titles: item = MyItem() item['title'] = titles. ...