I have created an Ionic 2 provider that gets sends login information to the server and then returns the data correctly. The problem is, that on the first click of the button that activates the provider and sends everything to the server, the first return is undefined
, while the second click returns the correct data.
Provider:
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the HttpProvider provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class HttpProvider {
constructor(public http: Http) {
console.log('Hello HttpProvider Provider');
}
get() {
}
post() {
}
login(username, password, url) {
let headers = new Headers();
headers.append("Content-Type", "application/json");
return this.http.post(url,
{"username": username,
"password": password,
}, {headers: headers})
.map(res => res.json());
}
}
TS File of the Page with the Button:
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import "rxjs/add/operator/map";
import { HttpProvider } from '../../providers/http-provider'
/**
* Generated class for the LoginPage page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-login-page',
templateUrl: 'login-page.html',
})
export class LoginPage {
username:any;
password:any;
stuff:any;
constructor(public navCtrl: NavController, public navParams: NavParams, private http: HttpProvider) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad LoginPage');
}
login() {
this.http.login(this.username, this.password, WORKING_IP_ADDRESS).subscribe(stuff => this.stuff = JSON.stringify(stuff));
console.log(this.stuff)
}
}
Some example input and output would be:
input:
username: bob
password: bob
output on first click:
undefined
output on second click where the login is successful:
{"id":"t326t34ergfsdy5u54terg324t37u567uygt5243y756u467u756y","ttl":54325432,"created":"2017-05-10T02:19:05.423Z","userId":63546543}
Can anyone see what is wrong with it?