【问题标题】:Retrive data with promises ( ionic and angular) [duplicate]用承诺(离子和角度)检索数据[重复]
【发布时间】:2018-08-28 17:10:50
【问题描述】:

开发人员您好,我正在尝试使用 promise 从我的 API 中检索数据,并在我的函数中使用这些值....这是我在服务中的函数

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

这是我在页面上的调用。问题是在函数之外调用 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) 工作,但第二个不工作 Screen Shot 谁能帮我解决这个问题,拜托!

【问题讨论】:

    标签: angular api ionic-framework promise provider


    【解决方案1】:

    因为它是异步的。

    所以,如果你想在从服务器获取数据后处理数据,逻辑应该在 promise/observable 订阅逻辑中。

    首先,让服务函数返回 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().
    }
    

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

    【讨论】:

    • 这不起作用,因为当它在承诺不显示后尝试 console.log(this.etudiantstage) 时
    • 我已经尝试过了,但是当我播种时,当我在承诺完成后尝试 console.log(this.etudiantstage) 时它没有显示结果,这在我想要的时候不起作用在其他函数中使用 promise 的返回值和
    • @mohamedfarjallah 你能添加完整的代码吗?组件和服务模块。
    • 对不起,这解决了我的问题
    猜你喜欢
    • 2016-10-03
    • 2015-10-27
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多