I'm trying to show the result from a Http.get() on my HTML, but it only shows when I have an error, I mean, if I get a 404 not found, it will print only a message on my HTML, but now that I do not have a 404 I have a response, I'd like to know how to print it using HTML. I'll explain the structure of my project...
I have a folder called provider where I have the list-service.ts, it contains the get...
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class ListServiceProvider {
private headers = new Headers({'Content-Type': 'application/json'});
private apiUrl = ""; // URL to web api
constructor(public http: Http) {
console.log('Hello I'm the ListServiceProvider Provider');
}
getList(): Promise<List[]> {
return this.http.get(this.apiUrl+'list/')
.toPromise()
.then(response => response.json().data as List[])
.catch(this.handleErrorPromise);
}
//if an error ocurred while doing api calls
private handleErrorPromise (error: Response | any) {
console.error(error.message || error);
return Promise.reject(error.message || error);
}
}
Now I've created a class on app folder (don't know if it's the best way to place it...) called List
export class List{
name: string;
surname: string;
phoneNumber: any;
imageURL: string;
email: string;
constructor(name: string,
surname: string,phoneNumber: any,
imageURL: string,
email: string){
this.name = name;
this.surname = surname;
this.phoneNumber = phoneNumber;
this.imageURL = imageURL;
this.email = email;
}
}
And now I have a List-list.ts file where I do the calls and save the objects as follows
import { Component, OnInit } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { List} from '../../app/list';
@IonicPage()
@Component({
selector: 'page-list-list',
templateUrl: 'list-list.html'
})
export class listListPage implements OnInit{
promiseList: Promise<List[]>
mList: List[];
errorMessage: String;
constructor(
public navCtrl: NavController,
public navParams: NavParams,
private listServiceProvider: ListServiceProvider
){}
ngOnInit(): void {
this.promiseList= this.listServiceProvider.getList();
this.promiseList.then(
list=> this.mList= list,
error => this.errorMessage = <any>error);
}
}
And finally on my HTML I have this...
<ul>
<li *ngFor="let list of promiseList | async">
Name: {{list.name}}, Surname: {{list.surname}}
</li>
</ul>
<div *ngIf="errorMessage">
<ion-card>
<ion-item>
<h2>There's an error</h2>
</ion-item>
</ion-card>
</div>
When I got a 404 error it shows the div but if I get a response from my API it didn't show the name and surname from list... What I'm missing?
async is the issue. Don't useasync` . It is used when you are using Observables. Removing it should work. Here you are using promise. I can help you if you want to do it observable way.this.promiseList= this.listServiceProvider.getList().then( ...