Issue
I want to get JSON type of data from backend, but the type of JSON must be generic. It has a generic number of values and generic keys, how can I correctly write the get method? For the moment I write 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 don't know what I must write in <>
brackets.
Solution
You can add the type as JSON. there is a type in typescript for that.
sample code
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'
},
{
id: 2,
name: "Franc",
lastModified: '2001-01-01 02:00:00'
},
{
id: 3,
name: "Andrew",
lastModified: '2021-01-01 02:00:00'
},
{
id: 11,
name: "Mark",
lastModified: '2020-01-01 02:00:00'
},
{
id: 12,
name: "Eric",
lastModified: '2020-02-01 02:00:00'
},
{
id: 8,
name: "Tony",
lastModified: '1990-01-01 02:00:00'
}
]
constructor() {
this.jsonObject = <JSON>this.arrayObj;
}
ngOnInit(): void {
}
In your case
getArticoliByDesc = (descrizione : string) => {
return this.httpClient.get<JSON>(`http://${this.server}:${this.port}/api/articoli/cerca/descrizione/${descrizione}`) //ALT + 0096 | ALT GR + '
}
But still creating a Model class which matched your api response would be the best way to do this. Even though api returns json, Angular http will convert it in to an object. Which you can then generalize by adding your model
Ex:
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}`) //ALT + 0096 | ALT GR + '
}
Answered By - Kelum Bandara
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.