Getting dynamic JSON data using TypeScript's generic types

I need to retrieve generic JSON data from the backend, with a variable number of values and keys. How should I modify my get method to handle this? Currently, my code looks like this:

getArticoliByDesc = (descrizione : string) => {
    return this.httpClient.get<{
      this.nomeChiave:
    }[]>(`http://${this.server}:${this.port}/api/articoli/cerca/descrizione/${descrizione}`) //ALT + 0096 | ALT GR + '
  }

I'm unsure what type to specify within the <> brackets.

Answer №1

If you want to include the type as JSON, there is a typescript type for that purpose.

Here is a sample code snippet:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-array-json-dates',
  templateUrl: './array-json-dates.component.html',
  styleUrls: ['./array-json-dates.component.scss']
})
export class ArrayJsonDatesComponent implements OnInit {
  jsonObject: JSON;

  arrayObj: any = [
    {
      id: 1,
      name: "john",
      lastModified: '2011-01-01 02:00:00'
    },
    // More data objects here...
  ]

  constructor() {
    this.jsonObject = <JSON>this.arrayObj;

  }

  ngOnInit(): void {

  
}

In your specific case, you can use the following code snippet:

getArticoliByDesc = (descrizione : string) => {
return this.httpClient.get<JSON>(`http://${this.server}:${this.port}/api/articoli/cerca/descrizione/${descrizione}`)
}

However, it is recommended to create a Model class that corresponds to your API response structure. This way, Angular HTTP will automatically convert the JSON response into an object that matches your model.

For example:

export class ApiModel{
   property1: string;
   property2: string;
   property3: string;
} 

getArticoliByDesc = (descrizione : string) => {
return this.httpClient.get<ApiModel>(`http://${this.server}:${this.port}/api/articoli/cerca/descrizione/${descrizione}`)
}

Answer №2

If you are unsure about the response type and don't mind about the typing, you can use:

const result = client.get<any>('URL');

If you know the response is an object but you are not familiar with its properties, you can do:

const result = client.get<{ [key: string]: unknown }>('URL');

// Alternatively, create an alias.
type Data = { [key: string]: unknown };

const result = client.get<Data>('URL');

// Or if you anticipate an array.
const result = client.get<Data[]>('URL');

If you require TypeScript to validate the type, you must ascertain the data type and define a corresponding typing. For instance:

type User = {
  name: string;
  email: string;
}

If you assume the response to be a User object => { name, email }

const result = client.get<User>('URL');

If you foresee the response to be an array of User objects => [ { name, email } ]

const result = client.get<User[]>('URL');

If you anticipate the response to be an array of specific string variables:

type KnownVariables = Array<'doctor' | 'programmer' | 'designer'>;

const result = client.get<KnownVariables>('URL');

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

There was an issue with the Ionic Angular Capacitor - FileOpener where it could not find the FileOpener activity:

In my Angular 12 Capacitor project, I'm attempting to launch a downloaded file in the user's preferred native application. To achieve this, I'm utilizing ionic-native/File and ionic-native/FileOpener. const dataType = event.body.type; ...

Retrieving the input[text] value in TypeScript before trimming any special characters

One of the tasks I am working on involves a form where users can input text that may contain special characters such as \n, \t, and so on. My objective is to replace these special characters and then update the value of the input field accordingl ...

What exactly is the concept behind the Strategy OnPush?

I am a beginner in the world of Angular2 with TypeScript. As I delve into my project, one concept that continues to elude me is the purpose of OnPush: changeDetection : ChangeDetectionStrategy.OnPush Despite my dedicated efforts in researching this top ...

Angular's let- directive does not assign a local variable

Having trouble setting a local variable within an <ng-template>, as it seems that let- is not functioning properly. Check out the demo here <ng-container *ngIf="data as d"> <ng-container *ngIf="false; else testBlock"></ng-containe ...

Error: Popover Not Functioning with Angular and Bootstrap 4.3

I'm attempting to implement the popover element sample code from the getbootstrap site. System Setup: Angular 8.0.0 JQuery 3.4.1 Popper.js 1.15.0 Bootstrap 4.3.1 ToolTip 1.6.1 In my angular.json file, I have included the necessary scripts "scripts ...

angular +webpack application unable to locate Jquery.widget

I recently set up a jhipster generated gateway app. I integrated a jquery plugin into my webpack.dev.js Within the assets folder, there is a scripts.js file which I included by adding its entry in vendor.ts. This script is now bundled in main.bundle.js T ...

Using Angular to send all form data to the API endpoint

Please bear with me as I am new and may ask small or incorrect questions. <form > <label for="fname">First name:</label> <input type="text" id="fname" name="fname"><br><br> <label for="lname">Last name:< ...

Angular 5 browser console displaying a communication from the server

I recently encountered an issue in Angular5 while trying to log into my account. Whenever there is a wrong password error, it displays a message in the browser console indicating server error 500. However, I do not want this message to be shown in the brow ...

Typescript raises an error when providing a potentially null value (that is not null) to an unnamed callback function

When dealing with a property that starts as null, how can I pass it to an anonymous callback function expecting a non-null value without TypeScript throwing errors? I've tried wrapping the function call in an if statement to check for null at the cal ...

Ways to Update the color of every element using a specified directive once a new theme is selected by the user

In the process of developing an online document builder using angular 4, I have created directives such as my-header and my-subheader to control the CSS styling properties of the angular components, like font size and boldness. My current challenge is cha ...

Struggling with storing information in a variable of type index

I devised a couple of interfaces to structure my data, as illustrated below: export interface BindingItem{ [property:string] : BehaviorSubject<string>; } export interface BindingObject{ [library:string] : BindingItem; } Within my service file, I h ...

Angular 2 plugin for creating interactive tooltips on SVG elements

Seeking to implement an interactive tooltip on an <svg:circle> element within my Angular 2 project, I opted for using Tooltipster (). Previously, the integration was smooth until I transitioned my project to angular 2. However, I am encountering dif ...

Issues with CORS functionality in Angular and NodeJS application causing disruptions

I am encountering issues with my Angular application that is Dockerized. When loading the application on Edge or Firefox, all the REST API requests needed to populate the homepage are not reaching the application. However, when I load the same page on Chro ...

Error message stating: "Form control with the name does not have a value accessor in Angular's reactive forms."

I have a specific input setup in the following way: <form [formGroup]="loginForm""> <ion-input [formControlName]="'email'"></ion-input> In my component, I've defined the form as: this.log ...

"Using RxJS 6 for a countdown timer in an Angular 6 application

Currently, I am working on implementing a countdown timer in Angular 6 using RxJS 6. My goal is to have the ability to subscribe to the results and reset the timer as needed: Here is what I have tried so far: const timer = interval(1000).pipe( take(4) ); ...

The 'wrapper' property is not present in the 'ClassNameMap<never>' type in Typescript

Hey there, I've been encountering a puzzling issue in my .tsx file where it's claiming that the wrapper doesn't exist. My project involves Material UI and Typescript, and I'm relatively new to working with Typescript as well as transiti ...

Best practices for working with Angular: How to handle nested subscribe calls effectively?

My dashboard component has an extended ngOninit function where I need to perform some verifications before the component loads. this.startupSubscription = this.accountService.getInfo().pipe( switchMap(account => { this.account = account; retur ...

Tips for sending an optional parameter to @Directives in Angular 2 using TypeScript

Here is a helpful guide on passing parameters to Angular 2 directives. <p [gridGroup]="gridGroup"></p> My goal is to have the parameter as optional so that it doesn't have to be included in every class referencing the html source. Curre ...

What is the best way to choose a random text from a dropdown menu that contains several div elements using Playwright?

web element Is it possible to choose a "random" text using div tags from a dropdown? I am attempting to pick any random country from the dropdown with the following code in Playwright: const selectCountry = this.page.locator('<this locator>&apos ...

Auth0 with auth0-lock will only authenticate when utilizing a debugger to carefully navigate through the code

As stated in the title, I am attempting to integrate auth0-lock with an Angular 2 SPA and an ASP.NET Core API. However, I am encountering difficulties with authentication during testing. My application is packed using webpack, and all unnecessary reference ...