I'm building an app with IONIC Angular, and I'm trying to print the result in HTML.
From console.log it works correctly, but from the view I can't get the data printed
json api
{
"matches1": {
"homeTeam": "Barcellona",
"awayTeam": "Real Madrid",
},
"matches2": {
"homeTeam": "PSG",
"awayTeam": "Lione",
}
}
home.page.ts
export class HomePage {
matches1: any;
homeTeam1: any;
awayTeam1: any;
result1: any;
private apiurl = 'https://myapi.xxx';
constructor(private httpService: HttpClient) {
this.getdata();
}
getdata() {
this.httpService.get(this.apiurl).subscribe(res => {
this.item = res['matches1']['homeTeam'];
console.log(this.item); <-- this work in console log
}, (err: HttpErrorResponse) => {
console.log (err.message);
}
);
}
}
home.page html
<ion-item *ngFor="let item of items">
{{item.homeTeam}}
</ion-item>
thanks!
This should do the work :
export class HomePage {
matches1: any;
homeTeam1: any;
awayTeam1: any;
result1: any;
items: any;
private apiurl = 'https://myapi.xxx';
constructor(private httpService: HttpClient) {
this.getdata();
}
getdata() {
this.httpService.get(this.apiurl).subscribe(res => {
this.items = Object.keys(res).map(function(key, index) {
return res[key];
});
}, (err: HttpErrorResponse) => {
console.log (err.message);
}
);
}
}
I like to use the json pipe (https://angular.io/api/common/JsonPipe), try this:
<pre>{{ items | json }}</pre>
Edit:
In your case, it might be item | json. Also, Hala Madrid !
You need to declare item in your Controller, and you can't use ngFor if your item is not a list. Right now your json is NOT returning an array, so if you can, it would be best to make it into a list of matches.
Your Json would look better if it was something like this:
{
"matches": [
{
"homeTeam": "Barcellona",
"awayTeam": "Real Madrid",
},
{
"homeTeam": "PSG",
"awayTeam": "Lione",
}
]
}
This way you can easily iterate through your list of matches in your controller
export class HomePage {
matches1: any;
homeTeam1: any;
awayTeam1: any;
result1: any;
item: string[]:
private apiurl = 'https://myapi.xxx';
constructor(private httpService: HttpClient) {
this.getdata();
}
getdata() {
this.httpService.get(this.apiurl).subscribe(res => {
res["matches"].forEach(match => this.item.push(match["homeTeam"]));
}, (err: HttpErrorResponse) => {
console.log (err.message);
}
);
}
}
Related
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);
}
);
}
I am trying to access the JSON data inside my angular template but I have no idea how to do it:
JSON DATA:
{
"data": {
"active_cryptocurrencies": 2050,
"active_markets": 15110,
"bitcoin_percentage_of_market_cap": 53.85,
"quotes": {
"USD": {
"total_market_cap": 207937227143.0,
"total_volume_24h": 10373130891.0
}
},
"last_updated": 1540293278
},
"metadata": {
"timestamp": 1540292653,
"error": null
}
}
mycomponent.ts
jsonData: any[];
private _url = 'https://api.coinmarketcap.com/v2/global/';
constructor(private http: Http) {
http.get("https://api.coinmarketcap.com/v2/global/")
.subscribe(response =>{
this.jsonData = response.json().data.quotes;
console.log(this.jsonData);
});
}
So I am trying to show these details in the angular template but it says cannot
find-a-differ-supporting-object-object-object-of-type-object-ngfor
Can you please help me as to how to go with this as json here is little messy?
I simply want to show the JSON data in my html template.
Edited:
import { Component, Input, OnInit,Injectable } from '#angular/core';
import { Http, Headers } from '#angular/http' ;
#Component({
selector: 'hello',
template: `
Hello, Angular
<ul *ngFor="let item of data">
<li>active_markets :{{item.active_markets}}</li>
<li>bitcoin_percentage_of_market_cap:{{item.bitcoin_percentage_of_market_cap}}</li>
<li>last_updated: {{item.last_updated}} </li>
<li>
<ul *ngFor="let q of item.quotes">
<li>total_market_cap: {{q.total_market_cap}}</li>
<li>total_volume_24h: {{q.total_volume_24h}}</li>
</ul>
</li>
</ul>
`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
#Input() name: string;
data:any=[];
private _url = 'https://api.coinmarketcap.com/v2/global/';
constructor(private http: Http) {}
async ngOnInit(){
let obj =(await this.http.get(this._url).toPromise()).json();
you should convert your json object
this.data= Object.keys(obj).map(function(e){
Object.keys(obj[e]).forEach(function(k){
if(typeof obj[e][k] == "object" && (obj[e][k]!=undefined || obj[e][k]!=null )) {
obj[e][k] = Object.keys(obj[e][k]).map(function(l){
return obj[e][k][l];
});
}
}return obj[e];
});
);}}
I have a server running on "localhost:3000". It displays data as JSON at e.g. "localhost:300/locations".
My "data.service.ts" includes this code:
path: string = 'http://localhost:3000'
constructor(private http: HttpClient) { }
// Locations
getAllLocations(): Observable<Location[]> {
let location = null;
this.http.get(this.path + '/locations')
.map((res => location = res))
.catch((error: any) => Observable.throw(console.log(error)));
return location;
}
In my result.component.ts I'm running this code:
constuctor(private dataservice: DataService) { }
ngOnInit() {
console.info(this.dataservice.getAllLocations());
}
I'm expecting to get as output all Locations as JSON, instead of this the output is "null".
Does anyone have a suggestion on how to make this work properly?
UPDATE:
Also tried this for the HTTP call:
getAllLocations(): Observable<Location[]> {
this.http.get<Location[]>(this.path + '/locations')
.pipe(
tap(items => console.info('fetched items'))
);
}
The output for this code is unfortunately: "Object { _isScalar: false, source: {...}, operator: {...} }"
Did you know that HttpClient#get returns an Observable? You can just return the get method in your method.
Secondly, you can set an interface to the method so that it'll return the JSON as typed.
Lastly, you can use template literals in your API URL.
/**
* Retrieves a list of locations.
* (TODO: Add better documentation here)
*/
getAllLocations(): Observable<Location[]> {
return this.http.get<Location[]>(`${this.path}/locations`);
}
You can then handle this in the actual component that calls this method:
constuctor(private dataservice: DataService) { }
ngOnInit() {
this.dataservice.getAllLocations().subscribe(result => {
console.log(result);
});
}
You have to return Observable from the service:
path: string = 'http://localhost:3000'
constructor(private http: HttpClient) { }
// Locations
getAllLocations(): Observable<Locations[]> {
return this.http.get(this.path + '/locations').pipe(
map((res => location = res)),
catch((error: any) => Observable.throw(console.log(error))));
}
And subscribe to it in the component.
constructor(private dataservice: DataService) { }
ngOnInit() {
this.dataservice.getAllLocations().subscribe(result => {
console.log(result);
})
}
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>
What I need to do is when i enters text inside textbox , i need to filter result inside li
I need do same as here
but this is done using ajax and i need to do using angular2 with data loading from .json file
my index.html is
<div id="search-container">
<div class="search" id="search-btn"></div>
<input #searchBox id="search" type="text" name="search-input" (keyup)="search(searchBox.value)">
<ul class="data-ctrl">
<li ng-repeat="i in items >i[0].name</li>
</ul>
</div>
My app.component.ts is
constructor(public http: Http,public _dmcService: DmcService) {
this._dmcService.getData('prc').subscribe(
data => { this.listingval= "prc"; this.assignJson(data); }
);
}
assignJson function from app.component.ts:
here i assigned data to heroes which is loaded from json file
assignJson(data: any) {
displayContent= data.teacher[0].libraryItems;
for (var i = 0; i <displayContent.length; i++) {
this.heroes[i] = [
{ id: i, name: data.teacher[0].libraryItems[i].display_title.slice(30)}
];
}
}
dmc.service.ts:
getData(filename: string) {
return this.http.get('assets/data/' + filename + '.json').map((res: Response) => res.json());
}
prc.json:
{
"isbn": "9781328694829",
"teacher": [
{
"component": "Core Resources",
"libraryItems": [
{
"id": "9781328694829-00001",
"display_title": "Practice- Ungroup from the Left or from the Right"
},
{
"id": "9781328694829-00002",
"display_title": "Reteach- Ungroup from the Left or from the Right",
}
]
}
}
search function in app.component.ts:
search(term: string): void {
this.searchTerms.next(term);
}
ngOnInit(): void {
let heroes: Observable<Hero[]>;
this.heroes = this.searchTerms
.debounceTime(300) // wait for 300ms pause in events
.distinctUntilChanged() // ignore if next search term is same as previous
.switchMap(term => term // switch to new observable each time
// return the http search observable
? this.heroSearchService.search(term)
// or the observable of empty heroes if no search term
: Observable.of<Hero[]>([]))
.catch(error => {
// TODO: real error handling
console.log(error);
return Observable.of<Hero[]>([]);
});
}
my heroesSearchService is as
#Injectable()
export class HeroSearchService {
constructor(private http: Http) {}
search(term: string): Observable<Hero[]> {
console.log('term:: ',term);
var str = this.http.get(`app/heroes/?name=${term}`)
.map((r: Response) => r.json().data as Hero[]);
return str;
}
}
export class Hero {
id: number;
name: string;
}
my current code not working, can anyone please help me with this.