0

Hi developers I am trying to retrieve data from my API with promises and work with these values in my functions.... this is my function in the service

getetudiant() {
    return new Promise((resolve, reject) => {
        this.http.get('http://localhost/eportfolio/etudiantprofile.php')
            .map(res => res.json())
            .subscribe(data => {
                resolve(data);
            }, error => {
                reject(error);
            })
    })
}
}

and this is my call on my page.ts the problem is whi call the etudiantstage outside the function it gives me an empty array

}
getAllStageItems(){
     this.etprofile.getetudiant().then((data: any) => {
        this.etudiantstage = data
        console.log(this.etudiantstage);
    });       

    console.log(this.etudiantstage);

    for(let item in this.etudiantstage){
        console.log(this.etudiantstage[item].cin);
        if(this.etudiantstage[item].cin == this.cin)
        this.validerAffiche = true;}
}

this first console.log(this.etudiantstage) work but the second doesn't work Screen Shot Can anyone help me to solve this problem, please !

Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37

1 Answers1

0

Because it is async.

So, if you want to handle data after getting data from servers, the logic should be inside promise/observable subscribe logics.

firstly, make service function to return observable

getetudiant() {
    return this.http.get('http://localhost/eportfolio/etudiantprofile.php')
            .map(res => res.json())   // should check Http or HttpClient since if you use HttpClient, you do not need to use res=>res.json().
}

and

getAllStageItems(){
     this.etprofile.getetudiant().subscribe((data: any) => {
        this.etudiantstage = data
        console.log(this.etudiantstage);

    // <= getting data and execute these logic here
    console.log(this.etudiantstage);

    for(let item in this.etudiantstage){
        console.log(this.etudiantstage[item].cin);
        if(this.etudiantstage[item].cin == this.cin)
        this.validerAffiche = true;}
    });       
}
Jihoon Kwon
  • 745
  • 5
  • 14