Home > Software engineering >  angular - json data to model
angular - json data to model

Time:02-01

With HttpClient I get a JSON data like below. The data comes in today. I can't send the incoming data into the model, I think I'm doing something wrong with the "map"

I can get the data without any problem, I just want to take the data under the data key and transfer it into the model.

Json

{
  "data": [
    {
      "description": "1",
      "createdUserId": "1",
      "createdUserName": "1",
      "companyId": 1,
      "status": "idle",
      "id": 1,
      "createdDate": "2022-01-27T09:11:00.32936",
      "updatedDate": "2022-01-27T06:10:44.123",
      "businessCode": "1"
    },
    {
      "description": "2",
      "createdUserId": "2",
      "createdUserName": "2",
      "companyId": 2,
      "status": "idle",
      "id": 2,
      "createdDate": "2022-01-27T09:11:12.2944465",
      "updatedDate": "2022-01-27T06:10:44.123",
      "businessCode": "2"
    }
  ],
  "errors": null
}

MaterialDemandsModel

export class MaterialDemandsModel {
  id: number | undefined;
  description: string | undefined;
  CreatedUserId: string | undefined;
  CreatedUserName: string | undefined;
  Status: string | undefined;
  CompanyId: number | undefined;
}

material-demand-component

import {MaterialDemandsModel} from "../../../models/material-demands/material-demands-model";

export class MaterialDemandComponent implements OnInit {
  displayedColumns: string[] = ['id', 'description', 'createduserid', 'createdusername', 'status', 'companyid'];

  materialDemands: MaterialDemandsModel[] = [];


  constructor(
    private demandsService:MaterialDemandService
  ) {

  }

  ngOnInit(): void {

    this.demandsService.getMaterialDemands().subscribe(data => {
      this.materialDemands =data;
      console.log(data);
    });

  }

}

services

import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {MaterialDemandsModel} from "../../models/material-demands/material-demands-model";
import {environment} from "../../../environments/environment";

@Injectable({
  providedIn: 'root'
})
export class MaterialDemandService {
  private apiUrl:string = `${environment.baseUrl}/api/materialdemand`;

  constructor(
    private httpClient:HttpClient
  ) {

  }

  public getMaterialDemands (){
    return this.httpClient.get<MaterialDemandsModel[]>(this.apiUrl);
  }

}

CodePudding user response:

If the data is already an object:

this.demandsService.getMaterialDemands().subscribe(data => {
      this.materialDemands = data.data;
    });

If the data is just a json string:

this.demandsService.getMaterialDemands().subscribe(json => {
      const data = JSON.parse(json);
      this.materialDemands = data.data;
    });

Also your MaterialDemandsModel has a few capital letters where they shouldn't be, they don't match the json keys.

  •  Tags:  
  • Related