Ionic 2, Http request only works after second call

Asked

Viewed 448 times

1

I created an application sidemenu and a provider (conexao-home.ts). On a test page I created the function buscarUsuarios (associated with a button), calling the function getRemoteUsers in the provider.

In the ionViewDidLoad put the same call to the function getRemoteUsers. When it loads the page, it makes the request and reads the data, but does not return the values in the return variable.

When I make the call via click button, it returns the data on the page.

How do I fix it? I know it’s a basic mistake, but I couldn’t fix it.

test ts.

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { ConexaoHome } from '../../providers/conexao-home';

@Component({
  selector: 'page-teste',
  templateUrl: 'teste.html',
})
export class Teste {

  public users: any;
  public teste: any;

  constructor(public navCtrl: NavController, public navParams: NavParams, public conexaoServico: ConexaoHome) {

  }

  buscarUsuarios() {
    this.users = this.conexaoServico.getRemoteUsers('Pegando os usuários');
    console.log('chamando...');
    console.log(this.users);
    console.log('retornando...' + this.users);
  }

  buscar() {
    this.teste = this.conexaoServico.getRemoteTeste('testando...');
    console.log(this.teste);
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad Teste');
    //this.buscarUsuarios();
    this.users = this.conexaoServico.getRemoteUsers('Pegando os usuários');
    console.log(this.users);
  }

}

html test.

<ion-header>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>Teste</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding="false">
  <button ion-button (click)="buscarUsuarios()">Pegar Dados</button>
  <br>
  <button ion-button (click)="buscar()">Pegar Dados 2</button>
  {{ teste }}
  <br>
  <ion-list>
    <button ion-item *ngFor="let user of users">
      <ion-avatar item-left>
        <img src="{{ user.picture.medium }}">
      </ion-avatar>
      <h2 text-wrap>{{ user.name.title }} {{ user.name.first }} {{ user.name.last }}</h2>
      <h3 text-wrap>{{ user.email }}</h3>
    </button>
  </ion-list>
</ion-content>

Provider connection-home.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class ConexaoHome {

  public usuarios: any;
  public areas: any;

  constructor(public http: Http) {
    console.log('Hello ConexaoHome Provider');
  }

  getRemoteUsers(tipo) {
    this.http.get('https://randomuser.me/api/?results=10').
    map(res => res.json()
    ).subscribe(data => {
      console.log(data.results);
      console.log(tipo);
      this.usuarios = data.results;
    });
    return this.usuarios;
  }

  getRemoteTeste(tipo) {
    console.log(tipo);
    return ('teste executado 2');
  }
}

Thank you.

  • In time: Ionic V 2.2.3

1 answer

1


this.users is async, this way you won’t know when it will contain some value. Besides, you are making a subscribe under the @injectable where it should only serve the data, who should observe is the page who’s calling you.

Make the following changes:

teste.ts:

   buscarUsuarios() {
    this.conexaoServico.getRemoteUsers('Pegando os usuários').subscribe(
    (users) => { console.log(users); this.users = users; }, 
    (err) => { console.error(err) },
    () => { console.log('done getting remote users') }
    );
  }



  ionViewDidLoad() {
    this.buscarUsuarios();
  }

conexao-home.ts:

getRemoteUsers(tipo) {
        return this.http.get('https://randomuser.me/api/?results=10').map(
        (response) => {
            return response.json().results;             
        }
    )
  }
  • It worked, thanks for the corrections.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.