Display data from a json object array - json

I am unable to loop through a json object array and display all data in separate divs.
Currently just using some mock data.
Team.servie.ts:
import { Http } from '#angular/http';
import { Observable } from 'rxjs/Rx';
import { Injectable } from '#angular/core';
import { Team } from './team';
#Injectable()
export class TeamService {
private _url = "http://jsonplaceholder.typicode.com/posts"
constructor(private _http: Http){
}
getPost() : Observable<Team[]>{
return this._http.get(this._url)
.map(res => res.json());
}
createPost(post: Team){
return this._http.post(this._url, JSON.stringify(post))
.map(res => res.json());
}
}
Component.ts:
import { Component, OnInit } from '#angular/core';
import { TeamService } from '../team.service';
#Component({
selector: 'About',
templateUrl: './about.component.html',
providers: [TeamService]
})
export class AboutComponent implements OnInit{
data;
isLoading = true;
constructor(private _teamService: TeamService){
/*this._teamService.createPost({userId: 1, title: "a", body: "b"});*/
}
ngOnInit(){
var text = "";
var i = 0;
this._teamService.getPost()
.subscribe(post => {
this.isLoading = false;
this.data = post;
console.log(post[0]);
});
}
}
Team.ts
export interface Team{
userId: number;
id?: number;
title: string;
body: string;
}
component.html:
<div *ngIf="isLoading">Getting data....</div>
<div let displayData of data>
<p> {{ displayData.id }}</p>
</div>
I know I am missing something, but i can't figure out what.
Any tips would be greatly appreciated.

use the *ngFor structureal directive like:
<div *ngFor="let displayData of data">
<p> {{ displayData.id }}</p>
</div>

Related

Having Issues Rendering api data in Material Angular Table

Good Afternoon,
I am trying to render the api data in a material table, but I am having issues connecting my NasaApiService to the dataSource array.
As of right now I am getting a "Type 'MatTableDataSource' is not assignable to type '[]'. error. Any help is much appreciated.
/*Nasa Service*/
import { Injectable } from '#angular/core';
import {HttpClient } from '#angular/common/http';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
export interface NasaStation {
name: string;
nametype: string;
id: string;
year: string;
recclass: string;
items: any;
}
#Injectable()
export class NasaApiService {
parsed: any;
constructor(private _http: HttpClient) {
}
getNasaData(): Observable<NasaStation> {
return this._http.get<NasaStation>('https://data.nasa.gov/resource/gh4g-9sfh.json');
}
}
/*nasa.component.*/
import { Component, OnInit } from '#angular/core';
import { NasaApiService} from '../nasa-api.service';
import {HttpClient} from '#angular/common/http';
import { MatTable,MatTableDataSource } from '#angular/material/table';
const api = 'https://data.nasa.gov/resource/gh4g-9sfh.json';
#Component({
selector: 'app-nasa',
templateUrl: './nasa.component.html',
styleUrls: ['./nasa.component.css']
})
export class NasaComponent implements OnInit {
data;
dataSource: [];
displayedColumns: string[] = ['Name', 'Name-type', 'ID', 'Year', 'Recclass'];
constructor(private _nasa: NasaApiService) {
}
ngOnInit(){
this._nasa.getNasaData().subscribe(data => {
this.dataSource = new MatTableDataSource(this.data);
this.data = data;
console.log(data);
})
}
}
ngOnInit(){
this._nasa.getNasaData().subscribe(data => {
this.data = data;
this.dataSource = this.data;
console.log(this.dataSource);
})
}
}
Was my final nasa.component code and I just passed datasource into Material Angular.

Angular6 error: the data which I am getting from api is in the string format,below is the response image

hi want to show the data from my api to my frontend (Angular 6), but this error comes up: I am using HttpClient method from angular 6 I am new to angular
Angular6 error: the data which I am getting from api is in the string format, I need to convert it to object, below is the response image
this is model.ts
export class Incident {
public Title: string;
public status: string;
constructor(Title: string, status: string) {
this.status = status;
this.Title= Title;
}
}
this is component
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { Incident } from '../../shared/incidents.model';
import { DataStorageService } from '../../shared/data-storage.service';
#Component({
selector: 'app-active-incident',
templateUrl: './active-incident.component.html',
styleUrls: ['./active-incident.component.css']
})
export class ActiveIncidentComponent implements OnInit {
incidents: Incident[];
constructor(private router: Router, private dataStorageService: DataStorageService) { }
ngOnInit() {
this.dataStorageService.getIncidents()
.subscribe(
(data: Incident[]) => this.incidents = data,
(err: any) => console.log(err),
() => console.log('All done getting incidents')
);
}
this is service
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Incident } from './incidents.model';
#Injectable()
export class DataStorageService {
constructor(private http: HttpClient) {}
getIncidents(): Observable<Incident[]> {
console.log('Getting all incidents from server');
return this.http.get<Incident[]>
('api/url');
}
}
my json
{
"Events": ["{'title': 'some title', 'Incident_Status': 'status'}",
"{'title': 'some title', 'Incident_Status': 'status'}"]
}
html view
<div class="card" *ngFor="let incident of incidents">
<div class="card-header">
<span class="badge badge-danger"></span>{{incident.Title}}
<span class="badge badge-danger"></span>{{incident.Incident_Status}}
</div>
</div>
You are trying to iterate an object instead of an array. This happens because the list of events are inside the Events key, but you aren't accessing it to extract the list of events. Instead you are using the root of the response object.
Corrected code:
ngOnInit() {
this.dataStorageService.getIncidents()
.subscribe(
(data: Incident[]) => this.incidents = data.Events, // <--
(err: any) => console.log(err),
() => console.log('All done getting incidents')
);
}

Angular 6 error: the data which I am getting from api is in the string format how to parse?

hi want to show the data from my api to my frontend (Angular 6) I am using HttpClient method from angular 6 I am new to angular
the data which I am getting from api is in the string format, I need to parse, below is the response image
this is model.ts
export interface Events {
IE_Incident_Start_Time: string;
IE_Start_time: string;
Title: string;
IE_Start_By: string;
Domain: string;
Impact: string;
IE_BU_Description: string;
}
this is component
enter code here
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { Incident } from '../../shared/incidents.model';
import { DataStorageService } from '../../shared/data-storage.service';
#Component({
selector: 'app-active-incident',
templateUrl: './active-incident.component.html',
styleUrls: ['./active-incident.component.css']
})
export class ActiveIncidentComponent implements OnInit {
incidents: Events[];
constructor(private router: Router, private dataStorageService:
DataStorageService) { }
ngOnInit() {
this.dataStorageService.getIncidents()
.subscribe(
(data: Events[]) => this.incidents = data,
(err: any) => console.log(err),
() => console.log('All done getting incidents')
);
}
this is service
enter code here
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Incident } from './incidents.model';
#Injectable()
export class DataStorageService {
constructor(private http: HttpClient) {}
getIncidents(): Observable<Events[]> {
console.log('Getting all incidents from server');
return this.http.get<Events[]>
('api/url');
}
}
html view
enter code here
<div class="card" *ngFor="let incident of incidents.Events">
<div class="card-header">
<span class="badge badge-danger"></span>{{incident.Title}}
<span class="badge badge-danger"></span>{{incident.Incident_Status}}
</div>
</div>
you can use the way as well
return this.dataStorageService.getIncidents()
.pipe(
map(jsonObj => Object.assign(new Events(), jsonObj),
catchError(error => console.log('Error!'))
);
Yes, you can do it this way.
this.dataStorageService.getIncidents().subscribe((data: Events[]) =>{
data.foreach(()=>{
this.incidents.push(JSON.parse(data));
})
},
(err: any) => console.log(err),
() => console.log('All done getting incidents')
);

Can't print nested JSON data with Angular 6

I'm learning to code and just ran into this issue with Angular 6 which I can't seem to solve. I was able to get JSON's data before but now that it's nested I don't know how to get it's data. This is what I've done so far
Service
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class TestService {
url = "http://localhost:80/assets/data/test.json";
constructor(private http:Http) { }
getTestWithObservable(): Observable<any> {
return this.http.get(this.url)
.map(this.extractData)
.catch(this.handleErrorObservable);
}
private extractData(res: Response) {
let body = res.json();
return body;
}
private handleErrorObservable (error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.message || error);
}
}
Component
import { Component, OnInit } from '#angular/core';
import { Observable } from 'rxjs';
import { TestService } from './test.service';
#Component({
selector: 'ngx-test',
styleUrls: ['./test.component.scss'],
templateUrl: './test.component.html',
})
export class TestComponent implements OnInit {
observableTest: Observable<any>
errorMessage: String;
constructor(private testService: TestService) { }
ngOnInit(): void {
this.testService.getTestWithObservable().subscribe(
res => {
let user = res[0]["users"];
let user_data = user["data"];
console.log(user_data["name"]);
}
);
}
}
JSON
[{
"id": 1,
"users": {
"user_id": 14,
"data": [{
"name": "James",
"age": 20
},
{
"name": "Damien",
"age": 25
}]
}
}]
HTML
<div *ngFor="let x of user_data; let i = index">
{{x.name}}
</div>
I'd appreciate if someone can point me out the solution or what I'm doing wrong.
You need to save the data in an instance property to access it. user_data is local to your function, you cannot access it in the template so you should use something like this :
export class TestComponent implements OnInit {
observableTest: Observable<any>
errorMessage: String;
user_data: any;
constructor(private testService: TestService) { }
ngOnInit(): void {
this.testService.getTestWithObservable().subscribe(
res => {
let user = res[0]['users'];
let user_data = user['data'];
console.log(user_data['name']);
this.user_data = user_data; // here
}
);
}
}
There is some problems with your code:
export class TestComponent implements OnInit {
observableTest: Observable<any>
errorMessage: String;
user_data: any;
constructor(private testService: TestService) {
}
ngOnInit(): void {
this.testService.getTestWithObservable().subscribe(
res => {
let user = res[0]["users"];
this.user_data = user["data"];
console.log(user_data["name"]);
}
);
}
}
In Angular >= 4, pipe methods is better to handle Observable
this.http.get(this.url)
.pipe(
filter(...),
map(...)
)
With HttpClient (Http is deprecated), the .json() is done for you. You don't need your extractData function.
You have to initialize your variable. And use "this" to refer to it.

Angular 4 - ERROR TypeError, ERROR CONTEXT DebugContext_

I'm rookie in Angular 4 and I need some help.
My code in console display error but in my template everything display correct.
Could someone help me understand what happend?
Error
ERROR TypeError: Cannot read property 'Tytul' of undefined
NewsDetailsComponent.html:7 ERROR CONTEXT DebugContext_ {view: Object, nodeIndex: 12, nodeDef: Object, elDef: Object, elView: Object}
news.ts
export interface News {
Ident: number;
Tytul: string;
Tresc: string;
Data: string;
}
news.service.ts
import { Injectable } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { News } from './news';
#Injectable()
export class NewsService {
private newsUrl = 'http://localhost:6128/getnews';
private headers = new Headers({ 'Content-type': 'application/x-www-form-urlencoded' });
private options = new RequestOptions({ headers: this.headers, withCredentials: true });
constructor(private http: Http) {}
getNews(): Promise<News[]> {
return this.http.get(this.newsUrl, this.options)
.toPromise()
.then(response => response.json().data as News[])
.catch(this.handleError);
}
getOneNews(id: number) {
const url = `${this.newsUrl}?Ident=${id}`;
return this.http.get(url, this.options)
.map(res => res.json());
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
news-details.component.ts
import { Component, Input, OnInit } from '#angular/core';
import { ActivatedRoute, Params } from '#angular/router';
import { Location } from '#angular/common';
import 'rxjs/Rx';
import 'rxjs/add/operator/switchMap';
import { News } from './news';
import { NewsService } from './news.service';
#Component({
selector: 'app-news-details',
templateUrl: './views/news-details.component.html',
providers: [NewsService]
})
export class NewsDetailsComponent implements OnInit {
#Input() news: News;
constructor(
private newsService: NewsService,
private route: ActivatedRoute,
private location: Location
) {}
ngOnInit(): void {
this.route.params
.switchMap((params: Params) => this.newsService.getOneNews(+params['id']))
.subscribe(res => this.news = res);
}
goBack(): void {
this.location.back();
}
}
news-details.component.html
<section class="header-box">
<button class="header-btn back icon-wroc" (click)="goBack();"></button>
<div class="header-title">Komunikat</div>
</section>
<section class="content-box">
<h2>{{ news.Tytul }} </h2>
<div class="content-content" [innerHTML]="news.Tresc"></div>
</section>
You are doing request to service which probably get data from the server.
The problem is simple that while you are doing request to server your object is null but view is already generated you have two options
First
<h2>{{ news?.Tytul }} </h2>
Second
<section class="content-box" *ngIf="news">
<h2>{{ news.Tytul }} </h2>
<div class="content-content" [innerHTML]="news.Tresc"></div>
</section>
Fist option will generate empty h1 and div, second option will not generate anything untill news is not null