Can't show data from local json file in browser - arrays

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"

Related

angular - json data to model

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.

How to convert API Object to Array

I stuck with this error ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
I am trying to fetch data from API but it's showing me this error, as I am still learning angular please guide me on how to tackle this kind of errors.
metadata-service.service.ts
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { Pincodes } from 'src/app/Model/Pincodes';
import { baseURL } from 'src/environments/environment';
#Injectable({
providedIn: 'root'
})
export class MetadataServiceService {
constructor(private http:HttpClient) { }
public GetPincodes() : Observable<any> {
console.log("Calling GetPincodes API")
return this.http.get("/Metadata/api/metadata/getpincodes") // My API Link
}
}
API consist of the following data
{
"program": null,
"version": null,
"dateTime": null,
"success": true,
"errorCode": null,
"errorMessage": null,
"message": "Pincodes read Successfully",
"data": [
{
"pincode": 400708,
"village": "Airoli",
"taluka": "Thane",
"district": "Thane",
"state": "Maharashtra"
},
{
"pincode": 416007,
"village": "Kaamba",
"taluka": "Kalyan",
"district": "Thane",
"state": "Maharashtra"
},
{
"pincode": 421102,
"village": "Atali",
"taluka": "Kalyan",
"district": "Thane",
"state": "Maharashtra"
},
{
"pincode": 421501,
"village": "Ambarnath",
"taluka": "Ambarnath",
"district": "Thane",
"state": "Maharashtra"
},
{
"pincode": 421503,
"village": "Ambeshiv",
"taluka": "Ambarnath",
"district": "Thane",
"state": "Maharashtra"
}
]
}
I am interested in the data array
Pincode.ts
export class Pincodes {
pincode : number
village : string
taluka : string
district : string
state : string
}
register-page.component.ts
import { Component, OnInit } from '#angular/core';
import { data } from 'jquery';
import { Pincodes } from 'src/app/Model/Pincodes';
import { MetadataServiceService } from 'src/app/shared/services/metadata-service.service';
import { Albums } from "src/app/Model/albums";
import { Observable, of } from 'rxjs';
import {MatTableDataSource, MatTableModule} from '#angular/material/table';
import { report } from 'process';
#Component({
selector: 'app-register-page',
templateUrl: './register-page.component.html',
styleUrls: ['./register-page.component.css']
})
export class RegisterPageComponent implements OnInit {
observeData : Pincodes[]
modifiedText: any;
PinSelected : any = {}
constructor(private _metadataService: MetadataServiceService) { }
ngOnInit(){
this._metadataService.GetPincodes()
.subscribe(data => {
this.observeData = data;
});
}
onPincodeSelected(val : Pincodes){
console.log("value" + val);
this.customFunction(val)
}
customFunction(val : Pincodes){
this.modifiedText = "The Selected Pin was " + val.pincode + " and selected District is " + val.village
console.log("modifiedText" + this.modifiedText);
console.log("Pincode Selected" + this.PinSelected);
console.log("observeData Selected" + this.observeData);
}
}
register-page.component.html
<select
[(ngModel)]="PinSelected"
(ngModelChange)="onPincodeSelected($event)"
>
<option *ngFor="let pin of observeData" [ngValue]="pin">
{{ pin.pincode }}
</option>
</select>
<div>
<p>{{ modifiedText }}</p>
</div>
Error: Cannot find a differ supporting object '[object Object]' of type 'object'.
Try this:
ngOnInit(){
this._metadataService.GetPincodes()
.subscribe(res=> {
this.observeData = res.data;
});
}

Export AmCharts to image/pdf in React application

Working on an application bootstrapped with create-react-app.
I need to export amChart to jpg/png/pdf formats.
I'm trying to export like in this codepen I've found: codepen export amchart example
var chart = AmCharts.makeChart("chart-header", {
"type": "pie",
"theme": "light",
"dataProvider": [ {
"country": "Czech Republic",
"litres": 301.9
}, {
"country": "Austria",
"litres": 128.3
}, {
"country": "UK",
"litres": 99
}, {
"country": "The Netherlands",
"litres": 50
}],
"valueField": "litres",
"titleField": "country",
"export": {
"enabled": true,
"menu": []
}
})
chart["export"].capture({}, function() {
this.toPNG({}, function(base64) {
console.log(base64)
})
})
But it doesn't work in my case. It gives me: Uncaught TypeError: chart.export.capture is not a function all the time.
So.. right or wrong, below is the simplified solution I've found.
On click "export" button, I make this.setState({ shouldExportChart: true }). In the "render" event listener I check whether it's true, if so, perform export and set to false.
In the same way, calling this.toJPG() we can export to JPG format.
For PDF generation I used jspdf, for archiving - jszip.
Dependencies in package.json:
"#amcharts/amcharts3-react": "^3.0.3",
"amcharts3": "^3.21.13",
"amcharts3-export": "github:amcharts/export"
"file-saver": "^1.3.3",
"fabric-webpack": "^1.6.0-rc.1"
Component.jsx:
import 'amcharts3'
import AmCharts from '#amcharts/amcharts3-react'
import 'amcharts3-export'
import 'fabric-webpack'
import FileSaver from 'file-saver'
const chartConfig = {
options: {
...,
"export": {
"enabled": true,
"menu": []
},
"listeners": [
{
event: 'rendered',
method: (e) => {
if (window.fabric) {
e.chart.export.capture({}, function () {
this.toPNG({}, function (base64) {
this.toBlob({
data: base64,
type: 'image/png'
}, (blob) => {
FileSaver.saveAs(blob, 'chart.png')
})
})
})
}
}
}
]
}
}
<AmCharts.React {...chartConfig} />

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> { }

AMcharts Map in angular js

I am currently working on AM Charts Maps. I want to implement below link in angularjs. How do I convert into angular js? Should i have to implement directive?
link
<div id="chartdiv"></div>
You can add the following files for the component.
map.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css']
})
export class MapComponent {
private id = "mapdiv";
private options;
makeChartConfig() {
return {
"type": "map",
"theme": "light",
"colorSteps": 10,
"dataProvider": {
"map": "indiaLow",
"areas": [{
"id": "IN-AN",
"value": 4447100
}, {
"id": "IN-AP",
"value": 626932
}, {
"id": "IN-KA",
"value": 5130632
}]
},
"areasSettings": {
"autoZoom": true
},
"valueLegend": {
"right": 10,
"minValue": "little",
"maxValue": "a lot!"
}
};
}
ngOnInit() {
this.options = this.makeChartConfig();
}
}
map.component.html
<amCharts [id]="id" [options]="options" [style.width.%]="100" [style.height.px]="500"></amCharts>

Resources