【问题标题】:Excution flow issue in ionic 2离子2中的执行流程问题
【发布时间】:2017-03-14 11:53:09
【问题描述】:

在这里我正在调用提供者(http 调用),它被成功调用但是 我遇到了执行流程问题。我希望输出为

4.3274
hi

but its printing

hi 
4.3274

<ion-buttons end>
                <button ion-button (click)="showcalculation()">Calculate</button>
            </ion-buttons>

             showcalculation(){    
                this.quoteServe.calSunShine().subscribe(data=>{     
                  console.log(data);
                })
                console.log("hi");   
              }

         **provider method:**

         calSunShine(){
            const body=new URLSearchParams();
            const header= new Headers();[enter image description here][1]   
            header.append('Content-Type', 'application/x-www-form-urlencoded');
            return this.http.post(this.base_url+"restInsertQuote/getsunshine",  body.toString(),{headers : header}).map(response => response.json()); 
          }


      [1]: https://i.stack.imgur.com/zHyQ3.png

【问题讨论】:

    标签: angular typescript ionic2


    【解决方案1】:

    它将运行 subscribe 函数 after 内的所有内容,因为 subscribeasync 并且其余代码将运行 sync.

    如果您真的想更改该流程,只需更改要在 subscribe 内调用的代码,例如:

     //Somewhere in your class
     let sunshine: any;
    
     showcalculation(){    
        this.quoteServe.calSunShine().subscribe(data=>{     
           //run this before
           console.log("hi");  
           //then
           console.log(data);
    
           // Extended example
           this.sunshine = data;
           // Let's use sunshine for something
           // This will run after and will print server data.
           this.doSomethingWithSunshine();
        });
        //This will run first and will print undefined.
        this.doSomethingWithSunshine();
     }
    
     doSomethingWithSunshine(): void {
         console.log(this.sunshine);
     }
    

    【讨论】:

    • 或者使用承诺
    • subscribe 中设置该值后,您将能够使用该值(this.sunshine),我将扩展我的答案以涵盖这种情况。如果此答案解决了您的问题,请记住将其设置为解决方案。
    猜你喜欢
    • 2021-06-27
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    相关资源
    最近更新 更多