how to iterate and display multiple objects from json in angular 2? - json

I am new to code Angular 2. My question is how to show JSON Format A with a proper formatting. As shown, the result includes whole objects (named Atom) I want to display.
If JSON format looks like B, I can show it using ngFor well. However, in the Json format A, I have to create multiple Atom objects explicitly from result then I can show them using NgFor.
I do not have sufficient knowledge about Angular 2 and JSON, if you have some idea about this, could you give me some guide for this and which way could be desirable solution?
Json Format A
{
"pageS": 25,
"pageN": 1,
"pageC": 2,
"result": [
{
"type": "A",
"id": "2425",
"tree": "false"
},
{
"type": "A",
"id": "1185",
"tree": "false"
},
{
"type": "A",
"id": "2680",
"tree": "false"
},
]
}
Json Format B
[
{"type":"A", "id": "2425", "tree":"false"},
{"type":"A", "id": "1185", "tree":"false"},
{"type":"A", "id": "2680", "tree":"false"}
]
app.component.ts
import {Component} from 'angular2/core';
import {Router} from 'angular2/router';
import {AtomService} from './service/atom';
import {User} from './datatype/User';
#Component({
selector: 'my-app',
template: `
<ul>
<li *ngFor="#atom of atoms">
{{atom.id}}
</li>
</ul>
`,
providers: [AtomService]
})
export class AppComponent {
atoms: Array<Atom>;
constructor(private service : AtomService) {
service.getAtoms().subscribe(res => this.atoms = res);
}
}
atom.service
import { Injectable } from 'angular2/core';
import { Http, Response } from 'angular2/http';
import 'rxjs/add/operator/map';
import {Atom} from '../datatype/Atom';
#Injectable()
export class AtomService {
constructor(private http: Http) {
this.http = http;
}
getAtoms() {
return this.http.get('./app/api/atoms.json')
.map( (responseData) => {
return responseData.json();
})
.map((atoms: Array<any>) => {
let result:Array<Atom> = [];
if (atoms) {
atoms.forEach((atom) => {
result.push(new Atom(atom.type, atom.id, atom.tree));
});
}
return result;
});
}
}

I'm not sure I understand what exactly do you want. You can read the results directly from the response, if you don't want to iterate and create new Atom objects.
<ul>
<li *ngFor="#atom of data.result">
{{atom.id}}
</li>
</ul>
But I think the way you have it now is actually better, as you should process the data, even though you can bind HTML directly to the result.

Related

How do I get my comments from local data.json to display on my page?

Trying to load the comments from my local json file but can't seem to get it to load properly. It's currently just showing a bulleted list of "0, 1, 2". Any ideas?
import React, { Component } from 'react'
import data from './../data'
class CommentList extends Component {
render () {
const elem = data.comments;
return (
<ul>
{Object.keys(elem).map(s => (<li>{s}</li>))}
</ul>
)
}
};
export default CommentList
{
"comments": [
{
"text": "Australian Shepherd!"
},
{
"text": "German Shepherd!"
},
{
"text": "Mutts all the way"
}
]
}
elem is an array so don't need Object.keys:
{elem.map(s => (<li>{s.text}</li>))}

Angular5 HTTPclient get issue with nested json

HttpClient.get in Angular 5 is not returning data if data is in a nested json format. The code below works for non-nested json data.
Would you please let me know if I miss anything or what would be a way to get the data?
Code:
import { HttpClient, HttpHeaders, HttpErrorResponse } from '#angular/common/http';
export class ReportService {...
searchByUser(userUrl: string): Observable<any> {
console.log('userUrl', userUrl);
return this.httpClient
.get(userUrl, { responseType: 'json' })
.catch((error: HttpErrorResponse) => {
return Observable.throw(error.status)
});
}
}
import { ReportService } from '../report.service';
this.reportService.searchByUser(userUrl).subscribe(data => {
console.log("Data :", data);
});
Nested JSON Sample Data returned by the userUrl:
[
{
"userId": "JX",
"location": "CHANTILLY, XX",
"fullName": "SMITH, JX L",
"userType": "P",
"userStatusDesc": "Active",
"occupationInfo": {
"occupationTitle": "HR GENERALIST HQ"
},
"miscInfo": {
"rankingPoints": 15,
"searchTermCount": 1
}
}
]
It looks like the issue was not with the HttpClient or nested JSON. I was able to have it working with the same JSON generated locally. And when I deployed the code it worked with the JSON generated under the same proxy.

How to get the length of JSON array?

I have a json url with a response of the following kind
[
{
"gender": "Female",
"age": 7,
"class": 2,
"subject": [
"",
"",
""
]
},
{
"gender": "Female",
"age": 8,
"class": 3,
"subject": [
"ab",
"cd",
"ef"
]
},
...
]
I want to find the length of this array
so in the angular app I am using
export class CustomComponent implements OnInit {
length: number;
constructor() {
this.length = Object.keys('www.url...').length;
console.log(length);
}
in .html I have
<p>{{ length }}</p>
I am getting 61 whereas the actual length is 44, but the console on the other hand is showing 0.
Where am I going wrong?
Any kind of help would be greatly appreciated. Thanks.
Easiest method.
import { Http } from '#angular/http';
export class CustomComponent implements OnInit {
length: number;
constructor(private http: Http){
this.http.request('www.url...',{method:'GET'}).map(response => response.json()).subscribe(result=>{
this.length=result.length;
});
}
}
Issue here is you are trying to execute Object.keys on url and not on
data , your url will be considered as string.
Solution is to use HttpClient :
// First get data from external url and then perform all operation
this.http.get('www.url...').subscribe(data => {
this.length = data.length;
console.log(length);
});

How can I iterate through JSON arrays and show data in a table in React

Here's my App.js file:
import React, { Component } from 'react';
import SongData from './songData';
export default class App extends Component {
render() {
return(
<div>
{JSON.stringify(SongData)}
</div>
)
}
}
SongData is a variable that's defined in and exported from another file called songData:
[{
"active": 1,
"createdAt": "2016-11-02T18:08:26.103Z",
"difficulty": "Medium"
},
{
"active": 0,
"createdAt": "2013-10-02T18:08:26.103Z",
"difficulty": "Difficult"
},
{
"active": 1,
"createdAt": "2015-12-02T18:08:26.103Z",
"difficulty": "Easy"
}
]
What I want to do is in my App.js file iterate through all the JSON arrays and print out the active, createdAt, and difficulty of each song in a table.
I unsuccessfully tried a for loop and map, but niether worked. Any ideas?
I think something like this should work:
import React, { Component } from 'react';
import SongData from './songData';
export default class App extends Component {
songItems = () => {
return SongData.map(s => {
return <li>{s.active}</li>
})
}
render() {
return(
<ul>
{this.songItems()}
</ul>
)
}
}
I'm making a method that's returning an array of List components, and then calling that method in the App's render method.

How to read in Angular 2 the JSON #text

Sorry, but I'm stagnant to read a very specific JSON value in Angular 2&4, where I can obtain and showing the name of the list BUT! but I can't find a way to show in the page, what I'm talking about for example in the JSON document I have this way: (obtained from http://www.last.fm/api/show/artist.getTopAlbums ) and I'm using the Postman to check all the contents, I can obtain the name of the Album and other things, BUT to obtain the #text to use the image it's weird
"topalbums": {
"album": [
{
"name": "The Very Best of Cher",
"playcount": 1663904,
"mbid": "a7e2dad7-e733-4bee-9db1-b31e3183eaf5",
"url": "https://www.last.fm/music/Cher/The+Very+Best+of+Cher",
"artist": {
"name": "Cher",
"mbid": "bfcc6d75-a6a5-4bc6-8282-47aec8531818",
"url": "https://www.last.fm/music/Cher"
},
**// +++++++++++++++++++THIS PART +++++++++++++++++++++!!!!!**
"image": [
{
// I'M TRYING TO USE THIS INFORMATION
"#text": "https://lastfm-img2.akamaized.net/i/u/34s/287bc1657795451399d8fadf64555e91.png",
"size": "small"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/64s/287bc1657795451399d8fadf64555e91.png",
"size": "medium"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/174s/287bc1657795451399d8fadf64555e91.png",
"size": "large"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/300x300/287bc1657795451399d8fadf64555e91.png",
"size": "extralarge"
}
]
},
What I want it's to obtain the "url" of the image, I try to obtain in this way:
artist.component.html
<div *ngFor="let list of albumes">
{{list.name}}
<hr>
<!-- Can't obtain the URL... -->
<img src="{{list.image[1].text}}" alt="">
</div>
artist.component.ts
import { Component, OnInit } from '#angular/core';
import {ActivatedRoute} from '#angular/router';
import {MusicService} from "../../services/music.service";
#Component({
selector: 'app-artist',
templateUrl: './artist.component.html',
providers: [MusicService]
})
export class ArtistComponent implements OnInit {
constructor(private service: MusicService, private route: ActivatedRoute) { }
albumes: any[];
songs: any[];
ngOnInit() {
this.route.params.map(params => params['mbid']).subscribe(
mbid => {
// Top Album
this.service.GetTopAlbumArtist(mbid).subscribe(topalbum => {
this.albumes = topalbum.topalbums.album;
console.log(topalbum.topalbums.image);
});
// Top Tracks
// this.service.GetTopTracksArtist(mbid).subscribe(toptracks => {
// this.songs = toptracks;
// });
}
)
}
}
First, if you want to get the first position of image array, you should access the position 0 (not 1)... also you don't have text but #text:
To solve your problem you can do this way:
src="{{list.image[0]['#text']}}"
or even better:
[src]="list.image[0]['#text']"