0

I have a page that calls an API to get some objects to be displayed, I make the call to the api in the constructor and subscribe to it, but before i get any data the page finishes loading with nothing to show.

constructor(public navCtrl: NavController, public userData: UserData, public navParams: NavParams, public profissional: ProfissionalData) {
  this.return_values_horarios_livres()
  console.log(this.lista_profissional)
}

return_values_horarios_livres(){
  return this.profissional.get_horarios_livres(this.clinica_id, this.especialidade_id).subscribe(
  data => { this.lista_profissional = data.objects;  this._save = data.objects; console.log("pegou aqi"); console.log(data.objects); console.log(this.lista_profissional)},
  err => {},
  ()=>{}
  )
}

That console logs prints undefined, which means that the data hasn't been loaded yet.

How do I wait to have something in the variable "lista_profissional" to load the page?

  • Use the data load in `resolve` of the route definition. – Aravind Jun 19 '17 at 17:24
  • I answered a similar question two days ago, take a look here:

    https://stackoverflow.com/questions/44598346/angular-4-binding-images-cannot-read-property-of-undefined/44598634#44598634

    – Rodolfo Pazos Rivas Jun 19 '17 at 17:26
  • If i use the ngIf it simply won't show anything, because when the page renders it doesnt have anything in the variable, it will only prevent me from having errors trying to access undefined. – Gabriel Almeida Jun 19 '17 at 17:41

2 Answers2

0

You might to hide splash when api return a response successfully or not, using .hide() method of SplashScreen Ionic component.

You can hide component with *ngIf directive from template until the server responds.

0

you can handle these problem in several way and based on your requirement

case 1 if your requirement is render the page and show data than you can use ngif or switch i will prefer switch

 <div [ngSwitch]='status'>
        <div *ngSwitchCase="'loading'">
          // you use simple text or some directive 
           <div>loading<div>
        </div>
        <div *ngSwitchCase="'active'">
            <form>
                <!-- the login inputs from earlier -->
            </form>
        </div>
    </div>

component

return_values_horarios_livres(){
  return this.profissional.get_horarios_livres(this.clinica_id, this.especialidade_id).subscribe(
  data => { this.lista_profissional = data.objects;  this._save = data.objects; console.log("pegou aqi"); console.log(data.objects); console.log(this.lista_profissional)},
  this.status = 'active';
  err => {},
  ()=>{}
  )
}

case2 if your requirement is first load the data and after render the template than you can use Resolvers in Angular2

https://stackoverflow.com/a/44437868/4667424

CharanRoot
  • 6,181
  • 2
  • 27
  • 45