Ionic, push page after successful http post

I have been trying so hard to make this work, not sure why this is not working. Below is the code which am using,

import {Http, Response, RequestOptions, Headers} from "@angular/http";

  loginCompleted() {
    console.log("loginCompleted()");
    this.navCtrl.push(TabsPage);
  }

login(callback) {
this.http
      .post("", body.toString(), options)
      .subscribe(function(response) {
        console.log("Login Response",response);
        this.loginResponse = JSON.parse(response.text());        
        callback
      });
}

Am trying to make a simple HTTP Post call and based on the response I want to push the TabsPage. But whats happening is Tabs page is getting pushed immediately after the HTTP post call is made. Can anyone tell what is the problem.

Don’t use callbacks if you can help it, use promises. Also db calls should be done from a provider, not a page.

From a simple page…

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { HttpClient, HttpHeaders } from '@angular/common/http';

interface ReturnedData{
  id: number;
  name: string;  
}

@IonicPage()
@Component({
  selector: 'page-enquiry-view',
  templateUrl: 'enquiry-view.html',
})
export class EnquiryViewPage {

  constructor(private http: HttpClient, private navCtrl: NavController) {
    this.loadDataThenGoToTheTabsPage();
  }

  async loadDataThenGoToTheTabsPage() {
    const returnedData = await this.postData();
    //by this point you have intellisense on 'returnedData'

    this.navCtrl.push(TabsPage, returnedData);
  }

  //Cleanly abstract away all the nonesense of the http.post - this should be in a provider
  postData(): Promise<ReturnedData> {

    return new Promise((resolve, reject) =>{
      const body: ReturnedData = { id: 123, name: 'whatever' };

      this.http.post<ReturnedData>('', body)
        .subscribe(data => {
          //You have the intellisense for 'data', the compiler knows it's a 'ReturnedData' object (as specified in the interface)
          console.log('Response data: ', data);
          resolve(data);
        });
    });
  
  }


}

Thanks a lot. As you suggested I have created a new provider and implemented this logic. It works fine now.

Nice one. Keep it up :slight_smile:

1 Like

Dont use function but fat arrow

()=>{}