Parsing JSON Data working only for template(HTML) but not for Component Class(Typescript) - json

I would like to parse a json file to use, and extract data.
I don't know why the data extracted from my code work only for my html, but is empty for my typescript code...
json file to parse :
[
{
"appleWatch": "generation_3",
"bracelets": ["model_1","model_2","model_3"]
},
{
"appleWatch": "generation_4",
"bracelets": ["model_1","model_4","model_5"]
}
]
Typescript of my component:
export class AppleKitComponent implements OnInit {
constructor(private httpService: HttpClient) {}
arrAppleWatch: AppleWatchModel[] = [];
selectedWatch: AppleWatchModel = null;
url = '../../assets/json/appleKit.json';
ngOnInit() {
this.arrAppleWatch = this.parseAppleWatchData();
console.log(this.arrAppleWatch.toString() + 'test');
}
parseAppleWatchData() {
this.httpService.get('../../assets/json/appleKit.json').subscribe(
data => {
this.arrAppleWatch = data as AppleWatchModel[]; // FILL THE ARRAY WITH DATA.
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
return this.arrAppleWatch;
}
}
My appleWatch model :
export class AppleWatchModel {
constructor(
public watch: string,
public bracelets?: string[],
public bracelet?: string
) {
}
}
HTML:
{{arrAppleWatch |json }}
My log should output :
[ { "appleWatch": "generation_3", "bracelets": [ "model_1", "model_2", "model_3" ] }, { "appleWatch": "generation_4", "bracelets": [ "model_1", "model_4", "model_5" ] } ]
but it just prints an empty string.
My html work and show the array :
[ { "appleWatch": "generation_3", "bracelets": [ "model_1", "model_2", "model_3" ] }, { "appleWatch": "generation_4", "bracelets": [ "model_1", "model_4", "model_5" ] } ]

There are a few issues with your implementation.
The httpService.get call call would be an async call. So it won't give you the data instantly. But you're trying to access it instantly. Hence you're not getting it in the Component Class.
Give this a try:
import { Component } from '#angular/core';
import { HttpClient, HttpErrorResponse } from '#angular/common/http';
export interface AppleWatchModel {
watch: string;
bracelets?: string[];
bracelet?: string;
};
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private httpService: HttpClient) {
}
arrAppleWatch: AppleWatchModel[] = [];
selectedWatch: AppleWatchModel = null;
ngOnInit() {
this.parseAppleWatchData()
.subscribe(res => {
this.arrAppleWatch = res;
console.log('test: ', this.arrAppleWatch);
});
}
parseAppleWatchData() {
return this.httpService.get<AppleWatchModel[]>('/assets/appleKit.json');
}
}
Here, we're returning an Observable<AppleWatchModel[]> from parseAppleWatchData. So we can subscribe to it in the ngOnInit to get the actual data.
Here's a Working Sample StackBlitz for your ref.

Your output is empty because you don't take the asynchronous nature of http requests into account. parseAppleWatchData is returned with the original arrAppleWatch value (which is []) before the http response is received. If you add some logs you will see B comes before A. You can also remove the return value.
export class AppleKitComponent implements OnInit {
constructor(private httpService: HttpClient) {
}
arrAppleWatch: AppleWatchModel [] = [];
selectedWatch: AppleWatchModel = null;
url = '../../assets/json/appleKit.json';
ngOnInit() {
this.parseAppleWatchData();
log('B', this.arrAppleWatch);
}
parseAppleWatchData() {
this.httpService.get('../../assets/json/appleKit.json').subscribe(
data => {
this.arrAppleWatch = data as AppleWatchModel []; // FILL THE ARRAY WITH DATA.
console.log('A', data);
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
}

Related

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 map certain JSON data to class and return observable

So I am trying to learn some basic Angular by creating an application that fetches and displays the current weather of a location using OpenWeather API.
This is what I have in my code currently:
app.component.ts:
import { Component } from '#angular/core';
import { WeatherService } from './weather.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [WeatherService]
})
export class AppComponent {
title = 'Ng-Weather';
cityName: string;
weather: Weather;
constructor(private weather: WeatherService) { }
search() {
this.weather.getWeatherbyName(this.cityName)
.subscribe(res => this.weather = res);
console.log(this.weather);
}
}
weather.service.ts:
import { Injectable } from '#angular/core';
import { Http, Response, URLSearchParams } from '#angular/http';
import { Observable } from 'rxjs';
import { Weather } from './weather';
#Injectable()
export class WeatherService {
APIurl = "http://api.openweathermap.org/data/2.5/weather";
Appid = "xxx";
weather: Weather;
constructor(private http: Http) { }
getWeatherbyName(name: string): Observable<any> {
let myParams = new URLSearchParams();
myParams.append('appid', this.Appid);
myParams.append('q', name);
return this.http.get(this.APIurl , { search: myParams} )
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
this.weather.city = body.name;
this.weather.description = body.weather[0].main;
this.weather.temp = body.main.temp;
console.log(this.weather);
}
private handleError(error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.message || error);
}
}
weather.ts:
export class Weather {
city: String;
description: String;
temp: String;
}
So basically I am trying to map a JSON returned from OpenWeather API and get only some parts of the data and not the whole thing. The JSON returned is like following:
{
"coord":{
"lon":80.28,
"lat":13.09
},
"weather":[
{
"id":802,
"main":"Clouds",
"description":"scattered clouds",
"icon":"03n"
}
],
"base":"stations",
"main":{
"temp":303.15,
"pressure":1008,
"humidity":79,
"temp_min":303.15,
"temp_max":303.15
},
"visibility":6000,
"wind":{
"speed":3.1,
"deg":210
},
"clouds":{
"all":40
},
"dt":1504805400,
"sys":{
"type":1,
"id":7834,
"message":0.0017,
"country":"IN",
"sunrise":1504744074,
"sunset":1504788314
},
"id":1264527,
"name":"Chennai",
"cod":200
}
When the above code is executed, I get this error:
weather.service.ts:32 Cannot set property 'city' of undefined
Also how do I return an observable of type Weather and return that variable weather and catch it on the app.component.ts?
You are not creating an instance of the weather object before assigning its properties. You can do that explicitly like this:
this.weather = new Weather();
this.weather.city = body.name;
this.weather.description = body.weather[0].main;
this.weather.temp = body.main.temp;
console.log(this.weather);
OR
You can do something like this:
this.weather = {
city: body.name,
description: body.weather[0].main,
temp: body.main.temp
}
console.log(this.weather);
And to answer the second part of your question, you should be able to do this:
getWeatherbyName(name: string): Observable<Weather> {
// your other code
}
private extractData(res: Response) {
// your other code
return this.weather;
}
And to answer the third part of your question ... Observables are asynchronous. This means that they do not immediately return a value. Rather they provide for definition of a callback function that is executed when the data is returned. That means that the data is undefined until the data is returned and the callback function is executed.
So if you want to access the returned data in your code, you need to do in WITHIN the callback function. Like this:
search() {
this.weather.getWeatherbyName(this.cityName)
.subscribe(res => {
this.weather = res;
console.log(this.weather);
});
}

How to get values from JSON webservice with 2 objects in Angular 2

I'm new in Angular 2 and I'm quite lost. I have a JSON web service responding to /rest/alertsDashboard. It returns something like:
{
"total": {
"totalOperations": 2573,
"totalOperationsAlert": 254,
"totalOperationsRisk": 34
},
"alerts": [
{
codAlert: "L1",
description: "Alert 1",
value: 1
},
{
codAlert: "L2",
description: "Alert 2",
value: 2
},
...
]
}
So I defined a DashboardComponent component and a AlertDashboardService service. I would like, for example, to display totalOperations and totalOperationsAlert. I don't know if I'm doing it in a correct way.
In dashboard.component.ts I have:
...
#Component({
selector: 'app-dashboard',
template: `
<p>{{totalAlertsDashboard.totalOperations}}</p>
<p>{{totalAlertsDashboard.totalOperationsAlert}}</p>
...
`
})
export class DashboardComponent implements OnInit {
totalAlertsDashboard: TotalAlertsDashboard;
alertsDashboard: AlertDashboard[];
constructor(private alertsDashboardService: AlertsDashboardService) { }
ngOnInit() {
this.alertsDashboardService.get().then(
response => {
this.totalAlertsDashboard = response.totalAlertsDashboard;
this.alertsDashboard = response.alertsDashboard;
}
);
}
}
In alerts-dashboard.service.ts I have:
...
export class AlertsDashboard {
totalAlertsDashboard: TotalAlertsDashboard;
alertsDashboard: AlertDashboard[];
}
export class TotalAlertsDashboard {
totalOperations: number;
totalOperationsAlert: number;
totalOperationsRisk: number;
}
export class AlertDashboard {
codAlert: string;
description: string;
value: number;
}
#Injectable()
export class AlertsDashboardService {
private headers = new Headers({ 'Content-Type': 'application/json' });
private url = environment.urlAPI + '/rest/alertsDashboard';
constructor(private http: Http) { }
get(): Promise<AlertsDashboard> {
var vm = this;
let params = new URLSearchParams();
return vm.http.get(vm.url, { search: params })
.toPromise()
.then(response => {
var responseJson: AlertsDashboard = response.json() ;
console.log(responseJson); // it prints the JSON correctly
return responseJson;
});
}
}
I hope you can help me with that.
try this :
ngOnInit() {
this.alertsDashboardService.get().then(
response => {
this.totalAlertsDashboard = response.total;
this.alertsDashboard = response.alerts;
}
);
}
In alerts-dashboard.service.ts
export class AlertsDashboard {
total: TotalAlertsDashboard;
alerts: AlertDashboard[];
}
template :
<p>{{totalAlertsDashboard?.totalOperations}}</p>

Angular ignoring JSON fields on Object instantiation

I am trying to query the wagtail API that will return JSON in a very unfriendly format.
{
"id": 3,
"meta": {
"type": "home.HomePage",
"detail_url": "http://localhost:8000/api/v1/pages/3/"
},
"parent": null,
"title": "Homepage",
"body": "<h2>cool an h2 fgf</h2>",
"main_image": {
"id": 1,
"meta": {
"type": "wagtailimages.Image",
"detail_url": "http://localhost:8000/api/v1/images/1/"
}
},
"header_image": {
"id": 1,
"meta": {
"type": "wagtailimages.Image",
"detail_url": "http://localhost:8000/api/v1/images/1/"
}
},
"show_in_menus": true,
"full_url": "/media/images/Background-4.original.jpg"
}
All I really want from that is a class like this.
export class HomePage {
id: number;
title: string;
body: string;
full_url: string;
}
But whenever I get back from the data back from my service and try and log it, it is undefined.
Is there any way for me to ignore the fields I don't want from a JSON in typescript?
The service I am using is:
import { Injectable } from '#angular/core';
import {Http, Response} from '#angular/http';
import {Observable} from "rxjs";
import {HomePage} from "./HomePage";
#Injectable()
export class HomePageService {
constructor(private http: Http){
}
getHomePage(GUID: number): Observable<HomePage>{
return this.http
.get("http://localhost:8000/api/v1/pages/" + GUID + "/")
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || {}
}
private handleError (error: Response | any) {
// In a real world app, we might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
And the component:
import {Component, OnInit, OnDestroy} from '#angular/core';
import {HomePageService} from './home-page.service';
import {ActivatedRoute} from '#angular/router';
import {HomePage} from "./HomePage";
#Component({
selector: 'app-home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.css'],
providers: [HomePageService]
})
export class HomePageComponent implements OnInit, OnDestroy{
id: number;
private sub: any;
public homePage: HomePage;
errorMessage: string;
constructor(private homePageService : HomePageService, private route: ActivatedRoute) {
}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.id = +params['id'];
});
this.homePageService.getHomePage(this.id)
.subscribe(
homePage => this.homePage = new HomePage(homePage),
error => this.errorMessage = <any>error,
() => console.log(this.homePage.full_url)
);
console.log(this.id);
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
homePage => this.homePage = new HomePage(homePage) - in your code I don't see a constructor defined for HomePage class. So when you pass the homePage object to it, nothing happens. Try this:
export class HomePage{
id: number;
title: string;
body: string;
full_url: string;
constructor(homePageObj: any)
{
if (homePageObj)
{
this.id = homePageObj.id;
this.title = homePageObj.title;
this.body = homePageObj.body;
this.full_url = homePageObj.full_url;
}
}
}

How can I sanitize css properties to use in template given from a data service

I need to generate sanitized css property to use with my component template to set the background image of the div:
<div *ngFor="let Item of Items"
[style.background-image]="Item.imageStyle
(click)="gotoDetail(Item.iditems)">
</div>
using data obtained through a data service. The component is:
import { Component } from '#angular/core';
import { Router } from '#angular/router';
import { DomSanitizer } from '#angular/platform-browser';
import { OnInit } from '#angular/core';
import { Item } from '../models/Item';
import { CollectionDataService } from '../services/CollectionData.service';
#Component({
selector: 'mainpage',
templateUrl: 'app/mainpage/mainpage.component.html',
styleUrls: ['app/mainpage/mainpage.component.css']
})
export class MainpageComponent implements OnInit {
Items: Item[];
ngOnInit() {
this.collectionDataService.getItems().subscribe(
Items => this.Items = Items
);
// Generates and sanitizes image links
this.Items.map(
(LItem) => LItem.imageStyle = this.sanitizer.bypassSecurityTrustStyle("url(template/images/"+LItem.iditems+".jpg)")
)
}
constructor(
private router: Router,
private sanitizer: DomSanitizer,
private collectionDataService: CollectionDataService
) {
}
gotoDetail($iditems: number): void {
this.router.navigate(['/viewer', $iditems]);
}
}
But it doesn't work because the statement that generates the sanitized property
this.Items.map(
(LItem) => LItem.imageStyle = this.sanitizer.bypassSecurityTrustStyle("url(template/images/"+LItem.iditems+".jpg)")
)
doesn't find the loaded data. The error that I'm seeing in the browser console is:
core.umd.js:3070 EXCEPTION: Uncaught (in promise): Error: Error in ./MainpageComponent class MainpageComponent_Host - inline template:0:0 caused by: Cannot read property 'map' of undefined
TypeError: Cannot read property 'map' of undefined
The data service is:
import { Injectable } from '#angular/core'
import { Http } from '#angular/http'
import { Item } from '../models/Item';
import { DomSanitizer } from '#angular/platform-browser';
#Injectable()
export class CollectionDataService {
constructor(
private http: Http,
private sanitizer: DomSanitizer
) { }
getItems() {
return this.http.get('app/mocksdata/items.json').map(
response => <Item[]>response.json().items
)
}
}
And the provided items.json:
{
"items": [{
"iditems": 1,
"imageStyle": ""
}, {
"iditems": 2,
"imageStyle": ""
}]
}
If I set static data in the component, instead of using the data service, everything works:
export class MainpageComponent implements OnInit {
Items: Item[];
ngOnInit() {
this.Items = [{
"iditems": 1,
"imageStyle": ""
}, {
"iditems": 2,
"imageStyle": ""
}]
// Generates and sanitizes image links
this.Items.map(
(LItem) => LItem.imageStyle = this.sanitizer.bypassSecurityTrustStyle("url(template/images/"+LItem.iditems+".jpg)")
)
}
How can I force the sanitizer statement to wait that the async data are fully loaded? Alternatively how can I generate sanitized properties directly in the service?
EDIT
The best answer comes from PatrickJane below:
Items: Item[] = [];
ngOnInit() {
this.collectionDataService.getItems().subscribe(Items => {
this.Items = Items;
this.Items.map(LItem => LItem.imageStyle = this.sanitizer.bypassSecurityTrustStyle("url(template/images/"+LItem.iditems+".jpg)"))}
});
}
I also solved this problem working directly in the service method (credits), but it is more verbose:
return this.http.get('app/mocksdata/items.json')
.map( (responseData) => {
return responseData.json().items;
})
.map(
(iitems: Array<any>) => {
let result:Array<Item> = [];
if (iitems) {
iitems.forEach((iitem) => {
iitem.imageStyle = this.sanitizer.bypassSecurityTrustStyle("url(template/images/"+iitem.iditems+".jpg)");
result.push(<Item>iitem);
});
}
return result;
}
)
The subscribe function is async so your map function called before the subscribe function run. So in this phase the array is undefined because you doesn't set any initial value.
The solution is to do this inside the subscribe function and to initialize the Items with empty array.
Items: Item[] = [];
ngOnInit() {
this.collectionDataService.getItems().subscribe(Items => {
this.Items = Items;
this.Items.map(LItem => LItem.imageStyle = this.sanitizer.bypassSecurityTrustStyle("url(template/images/"+LItem.iditems+".jpg)"))}
});
}