1

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?

10
  • You have syntax errors in your code, just look at the syntax highlighting. Commented Jun 22, 2017 at 13:48
  • @Musa .... that's because I've deleted the api url.... I'm not saying that my code isn't compiling, but thanks I'll edit that Commented Jun 22, 2017 at 13:50
  • Vous devez utiliser ngFor dans votre mlist. Pas dans votre promiseList. Your data is in your mList, your promiseList have the request http. Commented Jun 22, 2017 at 13:54
  • async is the issue. Don't use async` . 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. Commented Jun 22, 2017 at 13:56
  • Change component code to this . this.promiseList= this.listServiceProvider.getList().then( ... Commented Jun 22, 2017 at 13:57

2 Answers 2

1

You got too many issues to solve in the comments .

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 => {
                    let data = response.json().data as List[];
                    console.log(data);
                    return data;
                )
               .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);
    }

}

Component should be something like this .

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.listServiceProvider.getList()
         .then(
           list=> {this.mList= list; console.log(list)},
           error =>  this.errorMessage = <any>error);
   }

}

In your HTML it should be

<ul>
    <li *ngFor="let list of mList">
        Name: {{list.name}}, Surname: {{list.surname}}
    </li>
</ul>

UPDATE : Using rx.

First get your promise code to work. Then try this.

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/')
               .do(response => console.log('response',response)
               .map(response => response.json().data);                   
  }

}

Component

import { Component, OnInit } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';

import { List} from '../../app/list';

@IonicPage()
@Component({
  selector: 'page-list-list',
  templateUrl: 'list-list.html'
})
export class listListPage implements OnInit{
   mList$: Observable<List[]>;
   errorMessage: String;


  constructor(
    public navCtrl: NavController, 
    public navParams: NavParams,
    private listServiceProvider: ListServiceProvider
    ){}  

  ngOnInit(): void {
     this.mList= this.listServiceProvider.getList();
  }

}

Inside your HTML

  <ul>
        <li *ngFor="let list of mList | async">
            Name: {{list.name}}, Surname: {{list.surname}}
        </li>
    </ul>
Sign up to request clarification or add additional context in comments.

12 Comments

Thanks for you answer, but still without showing anything, is there any way to know if it's giving to me the correct result?
I put console.log statements. try now
it says undefined
which line response or component,
getList(): Promise<List[]> { return this.http.get(this.apiUrl+'list/') .toPromise() .then(response => console.log(response.json().data)) .catch(this.handleErrorPromise); }
|
1

Your data is in your mList:List[]. And you use *ngFor in your promiseList: Promise<List[]>

TS

ngOnInit(): void {
  this.listServiceProvider.getList().then(
           list=> this.mList= list, //mList contains all data from server side
           error =>  this.errorMessage = <any>error);


   }

HTML

<ul *ngIf="mList">
    <li *ngFor="let list of mList">
        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>

10 Comments

Ok look my update. Use this.listServiceProvider().then instead of this.mList= this.listServiceProvider.getList(); You need set mList in callback from your service.
How can I know if my response is OK?
.map(response => console.log(response.json().data)); in your service.
Type 'void' cannot be converted to type 'List[]'. doing this : .then(response => console.log(response.json().data) as List[])
Swtich your type to any for testing
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.