ionView hook doens't fire provider function in root page


#1

In provider bellow, i get a list of user to display in home page. If i push the HomePage, the hook ionViewWillEnter works fine, but if i enter as rootPage, is returned undefined for usuarios property.

What’s going wrong?

provider ConexaoHome.ts

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

@Injectable()
export class ConexaoHome {

  public usuarios: 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 => {
      this.usuarios = data.results;
    });
    return this.usuarios;
  }

}

Home.ts


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

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

  public users: any;

  constructor(public navCtrl: NavController, 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);
  }
  

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

Home.html


<ion-header>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>HOME</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>
  <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>

#2

I think this callback will fire only when is the first load. You need use a callback that runs when you enter or have the page cached, like ionViewDidEnter. Take a look on NavController.


#3

I try all the hooks, and only works if i push the HomePage and doens’t works when start a RootPage.


#4

Maybe you have a good reason for it, but why are subscribing inside the Injectable? Wouldn’t it be much better to subscribe in the actual page where you want to retrieve the data instead of doing this: this.users = this.conexaoServico.getRemoteUsers('Pegando os usuários');


    this.users = this.conexaoServico.getRemoteUsers('Pegando os usuários');
    console.log(this.users);

You’re trying to log this.users, but since it’s async you never know at that moment that this.users actually contains a value. What you should do instead, is take a look at how subscribers are meant to work. Something like this inside your service:

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

Now inside your page, subscribe to it like this:

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

Now in your ionViewWillEnter call buscarUsuarios() :

ionViewWillEnter() {
    console.log('ionViewDidLoad xxx Teste');
    this.buscarUsuarios();
  }

Ionic 2 function return problem
#5

Thank you for clearing my mistake. Now i understood the operation of subscribe.

but why are subscribing inside the Injectable?

You can tell me what is wrong? What i should read about it?