Ionic post request save to local storage


#1

Hi, i’m new with ionic and I’ve read a tutorial about making post requests.

The app is making this post request and save the data in my mysql database but if I click the “sign up” button, he don’t set the rootPage to HomePage and I’m not sure if the app save the data to the local storage because I don’t get any console.log and I don’t see any local storage in the browser.

AuthService

postData(credentials, type){
    
        return new Promise((resolve, reject) =>{
          let headers = new Headers();
          this.http.post(apiUrl+type, JSON.stringify(credentials), {headers: headers}).
          subscribe(res =>{
            resolve(res.json());
          }, (err) =>{
            reject(err);
          });
    
        });
    
      }

SignUp:

export class SignupPage {

  responseData : any;
  userData = {"username": "","password": "", "name": "","email": ""};

  constructor(public navCtrl: NavController, public authService:AuthServiceProvider) {
    
   } 

  signup() {
    this.authService.postData(this.userData, 'signup').then((result)=> {
      this.responseData = result;
      if(this.responseData.userData){
        console.log(this.responseData);
        localStorage.setItem('userData', JSON.stringify(this.responseData));
        this.navCtrl.setRoot(HomePage);
      }
      else{ console.log("Benutzer existiert bereits"); }
    }, (err) => {
      // Error log
    });
  }  

}

Thanks for your help


#2

Now I’ve try it with this

signuptest(){
  let headers = new Headers();
	    let data = this.userData

	    this.http.post(apiUrl+type, JSON.stringify(data), {headers: headers})
	      .subscribe(res => {
	      	console.log(res.json());
	      }, (err) => {
	      	console.log(err);
        });
}

But he say

Object { _body: error, status: 0, ok: false, statusText: "", headers: {…}, type: 3, url: null }

htaccess

RewriteEngine On

#RewriteBase /api/

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]

He post the data to the api and database, but how I can handle the response to save it to the localstorage?


#3

Just so you know, the code you posted is terrible. Not your fault. But it commits the explicit promise construction antipattern.

I recommend avoiding tutorials in general. Even if they are well written (and this one wasn’t), they get outdated fast. Always go first to official Angular docs, and official Ionic docs. For post requests, read this:
https://angular.io/guide/http#making-a-post-request