Ionic 带有Promise的数据(离子和Angular )[重复]

aelbi1ox  于 9个月前  发布在  Ionic
关注(0)|答案(1)|浏览(158)

此问题在此处已有答案

How do I return the response from an asynchronous call?(41个回答)
5年前关闭。
我试图从我的API中使用promise检索数据,并在我的函数中使用这些值.这是我在服务中的函数:

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);
            })
    })
}
}

字符串
这是我对pages. ts的调用,问题是在函数外部调用etudiantstage时,它给了我一个空数组。

}
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;}
}


第一个console.log(this.etudiantstage)工作,但第二个不工作:
x1c 0d1x的数据
谁能帮我解决这个问题,拜托!

vdgimpew

vdgimpew1#

因为它是一个。
所以,如果你想在从服务器获取数据后处理数据,逻辑应该在promise/observable subscribe逻辑中。
首先,使服务功能返回可观察

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().
}

字符串

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;}
    });       
}

相关问题