I am currently delving into Angular 2 and Ionic 2 (not to forget about NodeJS and TypeScript).
For testing purposes, I have a list of users available here. Eventually, I will be fetching real user data from an API connected to my database.
To handle this, I created a provider within my Ionic 2 project named test-service.ts
which contains the following code:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class PeopleService {
public users: any[];
constructor(public http: Http) {
this.users;
}
load(){
this.http.get('https://demo6000522.mockable.io/test')
.map(res => res.json())
.subscribe(
data => {
this.users = data;
console.log(this.users);
return Promise.resolve(this.users)
},
err => {
console.log("No users found!");
}
);
}
}
The retrieved user data is stored in an array called "peoples." You can view it by accessing the above URL.
In the file users.ts
, the following code is present:
import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
// importing the service here
import {PeopleService} from '../../providers/test-service';
@Component({
selector: 'page-users',
templateUrl: 'users.html',
// Importing the service to use the api
providers: [PeopleService]
})
export class UsersPage {
constructor(public navCtrl: NavController, public navParams: NavParams, public peopleService: PeopleService) {
this.loadPeople();
}
loadPeople(){
this.peopleService.load()
}
}
Finally, in the file users.html
:
<ion-header>
<ion-navbar>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Users</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item *ngFor="let user of users">
<p>{{ user.fistname }}</p>
<p>{{ user.lastname }}</p>
<p>{{ user.email }}</p>
</ion-item>
</ion-list>
</ion-content>
Although no errors are encountered and the data is successfully fetched in the console browser, there seems to be an issue with displaying it in the Ionic view as seen in the screenshot below:
https://i.sstatic.net/YI41h.png
Note: Disregard the WebSocket connection error mentioned. It's unrelated to the current query. Thank you.
How can I properly display my JSON data in the view?