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
– Murilo