Ionic 2, Http request only works after second call

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 ), which calls the function getRemoteUsers on provider .

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

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

How do I resolve this? I know it's a basic bug, but I could not figure it out.

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);
  }

}

test.html

<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-home.ts connection

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.

    
asked by anonymous 09.05.2017 / 19:30

1 answer

0

this.users is async , so you will not know when it will contain some value. What's more, you are doing subscribe under @injectable where it should only serve the data, it should be the page that is calling it.

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;             
        }
    )
  }
    
11.05.2017 / 15:26