I have created a basic app using the side menu template along with a provider called conexao-home.ts. Within a new page named teste, I have implemented a function called buscarUsuarios (linked to a button), which in turn calls the getRemoteUsers function within the provider.
In the ionViewDidLoad lifecycle hook, I have also included a call to the getRemoteUsers function. However, when the teste page is loaded, it successfully makes the HTTP call but doesn't return the data read back into the variable.
Interestingly, clicking the button triggers the function and displays the fetched data on the page. How can this issue be resolved?
teste.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('Fetching users');
console.log('calling...');
console.log(this.users);
console.log('returning...' + this.users);
}
buscar() {
this.teste = this.conexaoServico.getRemoteTeste('testing...');
console.log(this.teste);
}
ionViewDidLoad() {
console.log('ionViewDidLoad Teste');
//this.buscarUsuarios();
this.users = this.conexaoServico.getRemoteUsers('Fetching users');
console.log(this.users);
}
}
teste.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()">Fetch Data</button>
<br>
<button ion-button (click)="buscar()">Fetch Data 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 conexao-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 ('test executed 2');
}
}
Thank you.