Ionic Undefined after doing get

0

Hello I have problems with IONIC, every time I print console.log (this.items) it prints undefined, however console.log (data) prints without problems.

  • Ionic App Scripts: 3.2.0
  • Angular Core: 5.2.11
  • Angular Compiler CLI: 5.2.11
  • Node: 8.11.2

Note: I want to traverse that variable in the same controller, not in the view. I would greatly appreciate your help, regards.

export class AccederPage {
  items:any;
  usuario:String;
  clave:String;
  constructor(public navCtrl: NavController, public navParams: NavParams,public alertCtrl: AlertController, public http: HttpClient) {
  }

  ionViewDidLoad() {  
    console.log('ionViewDidLoad AccederPage');
  }
  login(){    
    this.http.get("https://xxx.com/yyy/empleados").subscribe(
      (data=>{
        this.items=data; 
        console.log(data);
      }),
      (
        error=>{
          console.log(error);
        }
      )
    );
   console.log(this.items);
    
asked by Jose Luis 01.10.2018 в 08:17
source

1 answer

0

It is normal for this to happen.

In the login function, what you do is first make a request to a URL:

this.http.get("https://xxx.com/yyy/empleados")

And you add a subscriber to the result of that call. But that call is executed asynchronously, that is, the request is made to the server and instead of waiting for the answer without doing anything, the JavaScript code continues to be executed.

Therefore, the following is executed:

console.log(this.items);

That returns undefined because there are no items yet.

A little later, the server response will arrive and the part of the corresponding subscription will be executed successfully:

(data=>{
        this.items=data; 
        console.log(data);
      }

There you set the value of this.items and therefore if you wrote console.log(this.items) you should show the received value without problem.

What you have to do is go through that variable within the code that receives the data, which would be in subscribe . Although probably if you want to transform it what you should do is use RxJS operators. For example, here they are commented on: link

    
answered by 01.10.2018 / 08:41
source