Sushanth
Sushanth

Reputation: 15

Excution flow issue in ionic 2

here in this I am making call to provider (http call),its getting called successfully but I am getting execution flow problem .I want output as

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.sstatic.net/zHyQ3.png

Upvotes: 0

Views: 36

Answers (1)

dlcardozo
dlcardozo

Reputation: 4013

It will run everything inside of the subscribe function after because subscribe is async and the rest of the code will run sync.

If you really want to change that flow just change the code to be called inside of the subscribe, like:

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

Upvotes: 1

Related Questions