Assign the http data in ionic 2 when loading the view

1

I can not understand why you do not assign the value to the variable this.userProfile I tried with promises and also do not assign any ideas?

Code:

import { Component, OnInit } from '@angular/core';
import { NavController, NavParams, LoadingController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import * as localforage from "localforage";

import { ProfileServices } from '../../providers/profile.services';

@Component({
    selector: 'page-profile',
    templateUrl: 'profile.html',
    providers: [ProfileServices]
})
export class Profile {

    public user: any;
    public userProfile: any;

    constructor(public navCtrl: NavController, private profile: ProfileServices, public params: NavParams, public storage: Storage, public loading: LoadingController) {
        this.getPerfilData();
        console.log("user profile" + this.userProfile); //Undefined ?       
    }

    getPerfilData() {
        this.presentLoadingDefault();

        this.storage.get('user').then((user) => {

            this.user = JSON.parse(user);

            this.profile.getProfile("token", this.user.idUser).subscribe(
                (data) => {
                    this.userProfile = data;
                    console.log("user profile" + this.userProfile); //Aqui me retorna la Data http success                   
                });

        });
    }

    presentLoadingDefault() {
        let loading = this.loading.create({
            content: 'Please wait...'
        });
        loading.present();
        setTimeout(() => {
            loading.dismiss();
        }, 2000);
    }

    ionViewDidLoad() {
        // this.getPerfilData();
    }

    ionViewWillEnter() {
        // this.getPerfilData();        
    }
}

Gist: link

    
asked by Jhonny Vanckruz 07.11.2016 в 19:32
source

2 answers

1

The most advisable thing is to use promises to deal with your assignment problems

import { Component, OnInit } from '@angular/core';
import { NavController, NavParams, LoadingController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import * as localforage from "localforage";

import { ProfileServices } from '../../providers/profile.services';

@Component({
    selector: 'page-profile',
    templateUrl: 'profile.html',
    providers: [ProfileServices]
})
export class Profile {

  public user: any;
  public userProfile: any;

  constructor(public navCtrl: NavController, 
              public profile: ProfileServices, 
              public params: NavParams, 
              public storage: Storage, 
              public loading: LoadingController) {
   // Solo usar para asignar variables
}

ngOnInit(){

    let loading = this.loading.create({
        content: 'Please wait...'
    });
    // Mostramos el loading
    loading.present();

    this.getPerfilData().then( (data) => {
        // Cuando la promesa termine cerramos el loading
        loading.dismiss();
        this.userProfile = data;

    }).catch( (error) => {
        console.log(error);
        // Si ocurre un error tambien cerramos el loading
        loading.dismiss();
    });

}

getPerfilData(): Promise<any>{

  return new Promise( (resolve,reject) => { 

    this.storage.get('user').then( (user) => {

        try{
          // Parsear json siempre es conveniente try-catch
          this.user = JSON.parse(user);

          this.profile.getProfile("token", this.user.idUser).subscribe(
          (data) => {
              // Retornamos
              resolve(data);           
          }, (error) => {
              reject(error);
          });

        }catch(error){
            reject(error);
        }

    },(error) => {
        reject(error);
    });

  });

}

ionViewDidLoad() {
    // this.getPerfilData();
}

ionViewWillEnter() {
    // this.getPerfilData();        
}
}

profile.html

Can be validated with "?", if userProfile is undefined it will not throw us error when we ask for its attributes

<ion-header>
  <ion-navbar>
    <ion-title>Profile</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-card>
    <div class="image_center" *ngIf="userProfile?.picUser">         
        <img [src]="userProfile.picUser">    
    </div>
    <ion-card-content *ngIf="userProfile?.firstName && userProfile?.lastName">
        <h1>{{ userProfile.firstName }} {{ userProfile.lastName }}</h1>         
        <div class="header_primary">
            Interest
        </div>
    </ion-card-content> 
  </ion-card>
</ion-content>
    
answered by 19.01.2017 в 16:51
0

@Jhonny Vanckruz, you're not losing the value outside the method, it's that the method has not been executed when you do the first console.log then the value does not exist yet. You should not try to access variables that receive their values within promises or observers outside of those promises or observers, because it is not known when the promise is going to be fulfilled. Rather, you must refactor your code to be used in the same promise or observer method.

import { Component, OnInit } from '@angular/core';
import { NavController, NavParams, LoadingController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import * as localforage from "localforage";

import { ProfileServices } from '../../providers/profile.services';

@Component({
    selector: 'page-profile',
    templateUrl: 'profile.html',
    providers: [ProfileServices]
})
export class Profile {

    public user: any;
    public userProfile: any;

    constructor(public navCtrl: NavController, private profile: ProfileServices, public params: NavParams, public storage: Storage, public loading: LoadingController) {
        this.getPerfilData();
        console.log("user profile" + this.userProfile); // No se ha cumplido el código dentro del observador      
    }

    getPerfilData() {
        this.presentLoadingDefault();

        this.storage.get('user').then((user) => {

            this.user = JSON.parse(user);

            this.profile.getProfile("token", this.user.idUser).subscribe(
                (data) => {
                    this.userProfile = data;
                    console.log("user profile" + this.userProfile); //Aqui sí se ha cumplido y puedes accederlo.                  
                });

        });
    }

    presentLoadingDefault() {
        let loading = this.loading.create({
            content: 'Please wait...'
        });
        loading.present();
        setTimeout(() => {
            loading.dismiss();
        }, 2000);
    }

    ionViewDidLoad() {
        // this.getPerfilData();
    }

    ionViewWillEnter() {
        // this.getPerfilData();        
    }
}

and to show it in your view:

<ion-header>
  <ion-navbar>
    <ion-title>Profile</ion-title>
  </ion-navbar>
</ion-header>
<ion-content padding>
    <ion-card>
        <div class="image_center">          
            <img [src]="userProfile.picUser">    
        </div>
        <ion-card-content *ngIf="userProfile !== undefined && userProfile !== null">
            <h1>{{ userProfile.firstName }} {{ userProfile.lastName }}</h1>         
            <div class="header_primary">
                Interest
            </div>
        </ion-card-content> 
    </ion-card>
</ion-content>
    
answered by 07.11.2016 в 19:53