Exploring the process of extracting information from a JSON file using Angular Observables

I have a JSON file named reportConfig that I need to access using Angular and TypeScript.

Below is the content of my JSON file:

{
  "accessToken": "12345",
  "style": "color",
  "projection": "globe",
  "zoomLevel": 5
  "markerScale": 1.1
}

In addition, I've created a new class called ConfigModel:

export class MapReportConfigModel {
  accesToken: string;
  style: string;
  projection: number;
  zoomLevel: number;
  markerScale: number;

  constructor(private httpClient: HttpClient) {}

  // Method to read JSON data
  getMapConfig(): Observable<ReportConfigModel > {
    let configData = `assets/reportConfig.json`;
    return this.httpClient.get<ReportConfigModel>(configData );
  }
}

Now, I have a child component named ReportContainer. My question is how can I call the getMapConfig() method from the child component?

export class ReportContainerComponent implements OnInit {
  
  constructor(
    private httpClient: HttpClient,
    private mapReportConfigModel: MapReportConfigModel
  ) {}

  ngOnInit(): void {}

  // Method to load initial map
  loadMap(): void {

  }

  private getMapConfigData(): void {
    this.httpClient.get(this.mapReportConfigModel);
  }
}

I have attempted to implement this but am not sure if it's correct. Any help on resolving this issue would be greatly appreciated. I want to call this method from the child component to fetch JSON data.

Answer №1

I am curious how I can make a call from the child component to access the getMapConfig() method.

To achieve this, you need to subscribe to the Observable returned by the getMapConfig method within the private mapReportConfigModel variable.

export class ReportContainerComponent implements OnInit {
  
  constructor(
    private mapReportConfigModel: MapReportConfigModel
  ) {}

  ngOnInit(): void {
    // Call the dependency from your component
    this.mapReportConfigModel.getMapConfig().subscribe((result) => {
       console.log(result);
    });
  }
}

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

Why am I encountering numerous errors while attempting to install Juice Shop?

My attempt to install the juice shop app from GitHub resulted in 63 errors showing up after running the command npm install. [riki@anarchy]: ~/juiceShop/juice-shop>$ npm install (Various warnings and engine compatibility issues) Multiple vulnerabilit ...

How to format a Date object as yyyy-MM-dd when serializing to JSON in Angular?

I have a situation where I need to display an object's 'birthDate' property in the format DD/MM/YYYY on screen. The data is stored in the database as YYYY-MM-DD, which is a string type. I am currently using bootstrap bsDatePicker for this ta ...

How to bypass middleware in Nest.js based on the header value

I am working on an application that utilizes nestjs and MiddlewareConsumer. Is there a way to skip a middleware based on a specific header value? I have reviewed the documentation and it appears that I can only skip middleware based on path or method, but ...

State management in React using hooks

Recently, I've been grappling with form validation while working on a signup form for my React app using Next.js. I've noticed that many sign up pages typically hide an "invalid" message until the user interacts with an input field. I attempted t ...

Looping through an array of objects with Angular 4's ngFor directive to dynamically display content

I am working with Angular 4 and I am attempting to iterate through an array of objects to present the data in Angular Material grid tiles. The code snippet from my HTML file (app.component.html) is as follows: <div class="list" *ngIf="listContacts == t ...

Stop ngOnChanges from being triggered after dispatching event (Angular 2+)

In Angular 2+, a custom two-way binding technique can be achieved by utilizing @Input and @Output parameters. For instance, if there is a need for a child component to communicate with an external plugin, the following approach can be taken: export class ...

What is the best way to find the clinic that matches the chosen province?

Whenever I try to choose a province from the dropdown menu in order to view clinics located within that province, an error 'TypeError: termSearch.toLowerCase is not a function' pops up. This part of the code seems confusing to me and any kind of ...

Filtering an array does not restrict the type of elements within it

I am facing a scenario where I have an interface containing two optional properties: interface A { one?: string; two?: string; } I want to pass these properties inside an array to a component that specifically requires string[] export const MyComponen ...

The operation to assign a value to property 'two' cannot be completed as it is currently undefined

I'm facing an issue with the code below and cannot figure out why I am encountering the error message. I have ensured that each object contains a value, so why is there a reference to 'undefined'? Cannot set property 'two' of unde ...

Issue encountered while deploying Node.js server on Render platform

I'm currently facing an issue while attempting to deploy a TypeScript server with Node.js to Render. I've provided the directory structure and deployment information below. Any insights or opinions you can offer would be greatly appreciated. Than ...

Utilizing Angular and Typescript for Enhanced Modal Functionality: Implementing Bootstrap Modals in Various Components

When working in Angular, I have a component called Modal. I need to open the same Modal Component from two different places. The catch is, I want the button text in the Banner image to say "Get Started Now". Check out the Image linked below for reference. ...

Error: "the cart variable in the ctx object has not been defined"

A project I'm currently working on involves a pizza ordering app, and my current focus is on implementing the Cart feature. Each user has their own cart, which includes specific details outlined in cart.ts import { CartItem } from './cartitem&a ...

When using TypeORM's save() method with an array of objects, the @PrimaryColumn() annotations are ignored, resulting

My current situation involves an entity called Point: @Entity() export class Point { @PrimaryGeneratedColumn('uuid') id: string; @IsUUID() @PrimaryColumn({ type: 'uuid', ...

Sending real-time data from the tRPC stream API in OpenAI to the React client

I have been exploring ways to integrate the openai-node package into my Next.js application. Due to the lengthy generation times of OpenAI completions, I am interested in utilizing streaming, which is typically not supported within the package (refer to he ...

What does the typeof keyword return when used with a variable in Typescript?

In TypeScript, a class can be defined as shown below: class Sup { static member: any; static log() { console.log('sup'); } } If you write the following code: let x = Sup; Why does the type of x show up as typeof Sup (hig ...

Enter a single unidentified character

As someone new to TypeScript, I have a question regarding my code. I am converting TypeScript into JavaScript to run in an environment where the window object has additional functions that I have declared on the TypeScript side like this: interface Window ...

Creating multiple objects with key-value pairs from JSON properties in TypeScript and React

I'm struggling to incorporate fetched data from an API into a Recharts line chart. The issue lies in mapping the JSON data properly. The API returns data that represents the count of predictions for each month, with a 0 value for months where no predi ...

Combining Layouts and Providers: A Guide to Using Both on a Single Page

I am facing an issue with my provider that is responsible for refreshing a token by making a request to the server. Additionally, I have a basic layout featuring a sidebar that I want to use only on a specific route. However, I am unsure about where to add ...

Encountering issues with React Nextjs - unable to utilize useState hook or

Hi everyone, I'm new to React and I think I might have overlooked something. I've been trying to create a simple registration form, but it seems like I'm having trouble changing the state. ` import {useState} from 'react' export ...

Personalizing the TabMenu or TabView Components in Angular with PrimeNg

Description: Currently tackling a project that involves recreating a widget similar to TabMenu/TabView in PrimeNg. Struggling with implementing different routerlinks on each button and customizing it to be more dynamic or resemble the provided image. Des ...