Reputation: 4728
I am trying to use http.post as described on https://ionicframework.com/docs/native/http/
I make an API call, I should get back some JSON and then if data.status
is success
then I set an element in the local storage and then change the root.
I am getting two errors when I try ionic serve
Operator '==' cannot be applied to types 'number' and 'string'.
This relates to the if(data.status == 'success') {
line
And
Property 'token' does not exist on type 'HTTPResponse'.
And this relates to the this.storage.set('myToken', data.token);
line
My full code is below. It seems like data
isn't being expected to be json
?
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { HTTP } from '@ionic-native/http';
import { FixturesPage } from '../fixtures/fixtures';
import { Storage } from '@ionic/storage';
@IonicPage()
@Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
email: string;
password: string;
constructor(public navCtrl: NavController, public navParams: NavParams, public http: HTTP, private storage: Storage) {
}
loginNow() {
this.http.post('https://api.domain.com/login', { email: this.email, password: this.password } , { headers: { 'Content-Type': 'application/json' } } ).then(data => {
if(data.status == 'success') {
this.storage.set('myToken', data.token);
this.navCtrl.setRoot(FixturesPage);
} else {
alert("Your login details are incorrect");
}
});
}
}
Upvotes: 0
Views: 959
Reputation: 458
You should map the response to json. To do so, import the rxjs map operator, and then add it to your post request:
loginNow() {
this.http.post('https://api.domain.com/login', { email: this.email, password: this.password } , { headers: { 'Content-Type': 'application/json' } } ).then(data => {
if(data.data.status == 'success') {
this.storage.set('myToken', data.data.token);
this.navCtrl.setRoot(FixturesPage);
} else {
alert("Your login details are incorrect");
}
});
}
EDIT as the documentation says, you need to use the data
property of the response
Upvotes: 1