angular - json data to model - arrays

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);
}
}

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.

Related

How to get a value on angular typescript in json

Here is my json respond using laravel spatie I created a respond that show if the user is have an Roles
{
"message": "Successfuly fetch all User",
"error": false,
"error_code": 200,
"line": "line 117 UserController.php",
"data": [
{
"id": 1,
"name": "dasdsa",
"email": "dasdsad#gmail.com",
"email_verified_at": null,
"created_at": "2020-04-22T13:37:41.000000Z",
"updated_at": "2020-04-22T13:37:41.000000Z",
"roles": [
{
"id": 2,
"name": "publisher",
"guard_name": "web",
"created_at": "2020-04-23T11:11:33.000000Z",
"updated_at": "2020-04-23T11:11:33.000000Z",
"pivot": {
"model_id": 1,
"role_id": 2,
"model_type": "App\\User"
}
}
]
},
{
"id": 2,
"name": "mdsadsadn",
"email": "dasdsad#gmail.coms",
"email_verified_at": null,
"created_at": "2020-04-23T10:37:10.000000Z",
"updated_at": "2020-04-23T12:04:46.000000Z",
"roles": [
{
"id": 2,
"name": "publisher",
"guard_name": "web",
"created_at": "2020-04-23T11:11:33.000000Z",
"updated_at": "2020-04-23T11:11:33.000000Z",
"pivot": {
"model_id": 2,
"role_id": 2,
"model_type": "App\\User"
}
}
]
}
]
}
and this is my code on angular 9.1.3 to get the value name in roles array
export class UserComponent implements OnInit {
roles:any;
result:any;
constructor(private _userService:UsersService) { }
ngOnInit(): void {
this.getallUser();
}
getallUser(){
this._userService.getallUsers().subscribe((event : HttpEvent<any>) => {
if (event.type === HttpEventType.Response) {
if (event.status == 200) {
let body = event.body;
let error = body.error;
let msg = body.message;
//alert(body);
// console.log(body.data);
if (!error) {
this.dataTbl.tblVal = body.data
this.roles = body.data.roles;
console.log(this.roles)
// this.result = this.roles.map(a => a.roles);
// console.log(this.result);
// console.log(this.dataTbl.tblVal)
}
}
}
this.dataTbl.tblLoad = false;
}, (err : HttpErrorResponse) => {
console.log(err);
});
}
}
Here is my service
import { Injectable } from '#angular/core';
import { HttpClient, HttpRequest, HttpHeaders } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class UsersService {
constructor(private _httpClient: HttpClient) {
}
getallUsers() {
return this._httpClient.get("http://localhost:8000/api/getallUser", {
observe: 'response', reportProgress: true });
}
}
My problem is I want to get the value of name in roles example:publisher but i cannot access on that object how to get that value the error is undefined I dont know what's wrong with my code thank you for the help

AngularJS Typescript loop through appsettings JSON

im having a really hard time looping through a specific section of the appsettings.json file i have. I am using angularjs with typescript any help would be greatly appreciated.
ServerConfig.ts
export interface ServerConfig {
campaigns: Campaign[];
}
export interface Campaign {
title: string;
description: string;
enabled: boolean;
}
Appsettings.json
{
"Settings": {
"Campaigns": [
{
"Title": "Test1",
"Description": "This is test 1",
"Enabled": true
},
{
"Title": "Test2",
"Description": "This is test 2",
"Enabled": true
}
],
},
}
Typescript
import { ServerConfig } from "../core/ServerConfig";
declare var config: ServerConfig;
export class IndexController {
constructor(
) { }
public $onInit() {
var campaigns = config.campaigns;
campaigns.forEach(function (data) {
console.log(data.title);
});
}
}
export var home: ng.IComponentOptions = {
controller: IndexController,
templateUrl: "/app/index.html"
};
The error I get is "campaigns.forEach is not a function"
The problem from what I can see is I didn't set it up correctly as an array.
ServerConfig.ts
export interface ServerConfig {
campaigns: Campaign;
}
interface CampaignItem {
title: string;
description: string;
enabled: boolean
}
interface Campaign extends Array<CampaignItem> { }

Can't show data from local json file in browser

I want to show JSON data in browser so that model, provider, storage and condition displays in separate divs.
There is no error in console and i can't figure out where is the problem.
Link updated for stackblitz, kindly have a look into it.
Github Repo
Here is the link for stackblitz.
iphone.json
{
"model": [
"iPhone 5",
"iPhone 5s",
"iPhone SE"
],
"provider": [
"Unlocked",
"AT&T"
],
"storage": [
"16",
"32"
],
"condition": [
"Brand New",
"Mint"
]
}
sell.service.ts
import { Injectable } from '#angular/core';
import { Observable } from "rxjs/Observable";
import { Http, Response } from "#angular/http";
import { HttpClient} from '#angular/common/http';
import "rxjs/add/operator/map";
export interface Staticdata {
model: Array<Model>;
provider: Array<Provider>;
storage: Array<Storage>;
condition: Array<Condition>;
}
export interface Model {
name: string;
}
export interface Provider {
carrier: string;
}
export interface Storage {
size: number;
}
export interface Condition {
quality: string;
}
#Injectable()
export class SellService {
fileUrl = '../static-data/iphone.json';
constructor(public http:HttpClient) {}
getData(){
return this.http.get(this.fileUrl);
}
}
sell-iphone.component.ts
import { Component, OnInit } from '#angular/core';
import { SellService, Staticdata } from "../shared/sell.service";
import * as data from "../static-data/iphone.json";
#Component({
selector: 'app-sell-iphone',
templateUrl: './sell-iphone.component.html',
styleUrls: ['./sell-iphone.component.css'],
providers: [ SellService ]
})
export class SellIphoneComponent implements OnInit {
constructor(public sellService: SellService){
}
ngOnInit() {}
staticData : Staticdata;
showData(){
return this.sellService.getData().subscribe((data: Staticdata) => this.staticData = {
model: data.model,
provider: data.provider,
storage: data.storage,
condition: data.condition
});
}
}
your json must be like:
{
"model": [
{
"name": "iPhone 5"
},
{
"name": "iPhone 5s"
},
{
"name": "iPhone SE"
}
],
"provider": [
{
"carrier": "Unlocked"
},
{
"carrier": "AT&T"
}
],
"storage": [
{
"size": "16"
},
{
"size": "32"
}
],
"condition": [
{
"quality": "Brand New"
},
{
"quality": "Mint"
}
]
}
Or you must transform the data you received. You can do it in the service better than in the component.
getData(){
return this.http.get(this.fileUrl).pipe(map((res:any)=>{
return {
model:res.model.map(m=>{return {name:m}}),
provider:res.provider.map(p=>{return{carrier:p}}),
storage:res.storage.map(s=>{return{size:s}}),
condition:res.condition.map(c=>{return{quality:c}})
}
})
);
}
If you're using angular-cli, you must put your file.json in the folder "assets"

Angular2 Typescript: error parsing JSON array

I am trying to parse a simple JSON structure with arrays using Angular 2 typescript.
JSON structure:
[
{
"_id": {
"$oid": "594156331900006500e5f0f7"
},
"username": "John Smith",
"place": {
"name": "vvio",
"point": {
"type": "Point",
"coordinates": [
51.5044484,
-0.1056523
]
}
},
"from": "2017-05-01",
"to": "2017-05-30",
"availabilities": [
{
"date": "2017-05-01",
"timeFrom": "20:00",
"timeTo": "21:00"
},
{
"date": "2017-06-01",
"timeFrom": "20:00",
"timeTo": "21:00"
},
{
"date": "2017-06-19",
"timeFrom": "15:25",
"timeTo": "15:25"
},
{
"date": "2017-06-19",
"timeFrom": "15:59",
"timeTo": "15:59"
}
],
"sports": [
"Sport5",
"Sport2"
]
}
]
I create this class to map the JSON structure:
export class Checkin {
_id: Id;
username: string;
place :Place;
from: string;
to: string;
availabilities: Availability[];
sports: string[];
}
export class Id {
$oid: string;
}
export class Place {
name: string;
point: Point;
}
export class Point {
type: string;
coordinates: number[]; // number?
}
export class Availability {
date: string;
timeFrom: string;
timeTo: string;
}
Here is the service:
getCheckins(userName : string): Promise<Checkin[]> {
var options = new RequestOptions({
headers : new Headers({
'Accept': 'application/json;q=0.9,*/*;q=0.8',
'Content-Type':'application/json',
})
});
console.log("checkin ");
const url = `${this.checkinUrl}${userName}`;
return this.http.get(url)
.toPromise()
.then(response => {
let result = response.json();
console.log("response "+JSON.stringify(result));
return result as Checkin[]})
.catch(this.handleError);
}
Here is how I call the service:
getCheckins(): void {
console.log("called get checkin ");
this.userService.getCheckins("test#outlook.com").then(checkins => this.checkins = checkins);
console.log("printing checkins "+JSON.stringify(this.checkins));
for (let checkin of this.checkins) {
console.log("checkin "+checkin.username);
}
}
Here is the error I get (comes from the for loop):
AppComponent.html:1 ERROR TypeError: Cannot read property 'length' of undefined
at CheckinComponent.getCheckins (checkin.component.ts:46)
at CheckinComponent.ngOnInit (checkin.component.ts:34)
at checkAndUpdateDirectiveInline (provider.ts:275)
at checkAndUpdateNodeInline (view.ts:456)
at checkAndUpdateNode (view.ts:417)
at debugCheckAndUpdateNode (services.ts:235)
at debugCheckDirectivesFn (services.ts:294)
at Object.View_AppComponent_0.co [as updateDirectives] (AppComponent.html:3)
at Object.debugUpdateDirectives [as updateDirectives] (services.ts:273)
at checkAndUpdateView (view.ts:345)
It seems that I am not able to parse the json response into the json class..
Any help appreciated.

app/mocks.ts(1,2): error TS1109: Expression expected

I'm learning Angular and after some time I've run into this problem with a mocks.ts file:
1) mocks.ts looks like this:
#import { Races } from './races';
export const RACES: Races[] = [{
"id": 1,
"name": "Daytona Thunderdome",
"date": new Date('2512-01-04T14:00:00'),
"about": "Race through the ruins of an ancient Florida battle arena.",
"entryFee": 3200,
"isRacing": false
}, {
"id": 2,
"name": "San Francisco Ruins",
"date": new Date('2512-07-03T20:00:00'),
"about": "Drift down the streets of a city almost sunk under the ocean.",
"entryFee": 4700,
"isRacing": true
}, {
"id": 3,
"name": "New York City Skyline",
"date": new Date('2512-07-12T21:00:00'),
"about": "Fly between buildings in the electronic sky.",
"entryFee": 4300,
"isRacing": true
}];
2)I'm importing Races from races.ts file, which looks like this:
export class Races {
"id": number;
"name": string;
"date": string;
"about": string;
"entryFee": number;
"isRacing": boolean;
}
3) And than I'm importing RACES to races.component.ts, which looks like this:
import { Component } from '#angular/core';
import { Races } from './races';
import { RACES } from './mocks';
#Component({
selector: 'races',
templateUrl: 'app/races.component.html',
styleUrls: ['app/races.component.css']
})
export class RacesComponent {
races: Races[];
cash = 10000;
ngOnInit() {
this.races = RACES;
};
// Write your function here
totalCost() {
var sum = 0;
for(let race of this.races) {
if(race.isRacing) {
sum += race.entryFee;
}
}
return sum;
};
}
Any help is very much appreciated!
Thanks!

Resources