I was recently learning how to use Ionic and I was trying to make a login page for user authentication by calling an Api.
My problem is that I have not found any tutorial, nor guide, sufficiently clear and updated. Not even in the official documentation is explained in detail. So I do not really know how to do it. I leave my code to see if someone can guide me a little.
I used link as an api to test.
Rest.ts:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class RestProvider {
username: string;
loginURL = 'https://jsonplaceholder.typicode.com/users';
access: boolean;
constructor(public http: HttpClient) {
}
public login(credentials) {
if (credentials.username === null || credentials.id === null) {
return Observable.throw("Please insert credentials.");
} else {
return Observable.create(observer => {
this.http.post(this.loginURL, JSON.stringify(credentials))
.subscribe(res => {
console.log(res);
}, (error) => {
console.log('por aquí');
console.log(error);
});
setTimeout(() => {
observer.next(this.access);
}, 500);
setTimeout(() => {
observer.complete();
}, 1000);
}, err => console.error(err));
}
}
Login.ts
import { Component } from '@angular/core';
import { NavController, LoadingController, Loading, AlertController,
NavParams } from 'ionic-angular';
import { TabsPage } from '../tabs/tabs';
import { RestProvider } from '../../providers/rest/rest';
@Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
loading: Loading;
credentials = { username: '', id: '' };
isLogged: boolean;
constructor(public navCtrl: NavController,
public restProvider: RestProvider,
public loadingCtrl: LoadingController,
private alertCtrl: AlertController) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad LoginPage');
}
doLogin() {
this.showLoading()
console.log(this.credentials);
this.restProvider.login(this.credentials).subscribe(allowed => {
if (allowed) {
console.log(allowed);
this.navCtrl.setRoot(TabsPage);
} else {
console.log(allowed);
this.showError("These credentials do not match our records.");
}
},
error => {
this.showError(error);
});
}
showLoading(){
this.loading = this.loadingCtrl.create({
content: 'Authenticating...',
dismissOnPageChange: true
});
this.loading.present();
}
showError(text) {
this.loading.dismiss();
let alert = this.alertCtrl.create({
title: 'Fail',
subTitle: text,
buttons: ['OK']
});
alert.present();
}
The code itself does not give an error or anything, but when authenticating what the "allowed" returns is an "undefined" and I do not know how to proceed. Thanks for the help and for your time.