Issue
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 which 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)
works but the second doesn't work:
Can anyone help me to solve this problem, please !
Solution
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;}
});
}
Answered By - Jihoon Kwon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.