Login using API in Ionic 6 - ionic-framework

## login.page.ts ##
import { Component, OnInit } from '#angular/core';
import { AuthService } from 'src/services/auth/auth.service';
import { NavController } from '#ionic/angular';
import { AlertService } from 'src/services/alert/alert.service';
import { NgForm } from '#angular/forms';
#Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss']
})
export class LoginPage implements OnInit {
constructor(
private authService: AuthService,
private navCtrl: NavController,
private alertService: AlertService
) { }
ngOnInit() {
}
onLogin(form: NgForm) {
this.authService.login(form.value.username, form.value.password).subscribe(
() => {
this.alertService.presentToast("Logged In");
this.navCtrl.navigateRoot('/welcome');
},
error => {
console.log(error);
},
() => {
this.alertService.presentToast("Failed");
this.navCtrl.navigateRoot('/login');
}
);
}
}
## login.page.scss ##
ion-content.background{
--background: url(../../assets/img/staffandtruck.jpg) 0 0/100% 100% no-repeat;
}
## login.page.html ##
<ion-content padding class="background">
<ion-card>
<img src="assets/img/logo2.png"/>
</ion-card>
<ion-card>
<ion-card-content>
<form #form="ngForm" (ngSubmit)="onLogin(form)">
<ion-item>
<ion-icon slot="start" name="person-circle"></ion-icon>
<ion-label position="floating">Staff ID</ion-label>
<ion-input type="email" name="username" ngModel required></ion-input>
</ion-item>
<ion-item>
<ion-icon slot="start" name="key"></ion-icon>
<ion-label position="floating">Password</ion-label>
<ion-input type="password" name="password" ngModel required></ion-input>
</ion-item>
<ion-card-content>
<ion-button expand="block" color="primary" type="submit">Log in</ion-button>
</ion-card-content>
</form>
</ion-card-content>
</ion-card>
</ion-content>
i am new here and beginner in Ionic Framework. Is there anyone can help me and teach me on how to create a login using API that call username and password without create a Model for User? I don't know how to startup and implement this API. This is my environment setup for Ionic.
My environment setup for Ionic. This is for environment service that calling API for login EnvService.ts. This is for auth service AuthService.ts. But, that all not functioning as I wish.

Related

How to pass data to another page from Input Form in IONIC 5

I have an input form with 3 text input. The only thing i want it is to send this 3 datas to another page that i called "Identity". I'd like to know how can do to send this 3 datas to another page using ionic 5. I want to create a signing step by step style. someone can help please?
REGISTER.PAGE.HTML
<ion-content fullscreen="true" class="background-contact">
<div class="fixed">
<div class="div-3">
<div align="center">
<b>IDENTIFICATION</b>
</div>
<ion-label position="stacked" class="title">E-mail</ion-label>
<div align="center" class="input-class">
<ion-input autofocus="true" ngModel name="email" type="email" placeholder="informez votre email"></ion-input>
</div>
<div class="line">
<ion-label position="stacked" class="title">Mot de passe</ion-label>
<div align="center" class="input-class">
<ion-input ngModel name="password" type="password" placeholder="informez votre mot de passe"></ion-input>
</div>
</div>
<!-- <div class="line">
<ion-label position="stacked" class="title">Téléphone</ion-label>
<div align="center" class="input-class">
<ion-input autofocus="true" ngModel name="phone" type="text" placeholder="Tapez votre numéro de tel" (keypress)="numberOnlyValidation($event)"></ion-input>
</div>
</div> -->
<div class="line">
<ion-label position="stacked" class="title">Pays</ion-label>
<div align="center" >
<ion-select cancelText="Fermer" okText="Confirmer" ngModel name="cod_country">
<ion-select-option value="">Dans quel pays êtes-vous?</ion-select-option>
<ion-select-option value="{{item?.id}}" *ngFor="let item of country">{{item?.name}}</ion-select-option>
</ion-select>
</div>
</div>
<div class="line">
<div align="center" class="input-class">
<ion-button (click)="goToAboutPage()" expand="block" color="primary"><ion-spinner *ngIf="loading"></ion-spinner> CONFIRMER <ion-icon name="checkmark-done"></ion-icon></ion-button>
</div>
</div>
</div>
</div>
</ion-content>
RESGISTER.PAGE.TS
import { Component, OnInit } from '#angular/core';
import { AlertController, NavController, ToastController } from '#ionic/angular';
import { AuthService } from 'src/app/services/auth.service';
import { NgForm } from '#angular/forms';
import { AlertService } from 'src/app/services/alert.service';
import {IdentityPage} from 'src/app/identity/identity.page';
import { Router } from '#angular/router';
#Component({
selector: 'app-register',
templateUrl: './register.page.html',
styleUrls: ['./register.page.scss'],
})
export class RegisterPage implements OnInit {
loading: boolean;// loading chamando
country: any;
password:any;
private cod_country;
constructor(
private authService: AuthService,
private navCtrl: NavController,
private alertService: AlertService,
public alertController: AlertController,
private toast: ToastController,
private router: Router,
) {
this.getCountry();
}
ngOnInit() {
}
//Get all country list
getCountry(){
this.authService.getCountry().subscribe(country=>{
this.country = country;
})
}
// navigate to about page
goToAboutPage(data) {
this.router.navigate(['/identity'],{
queryParams:data
})
}
}
There are Multiple Ways to pass data from 1 page to other page.
Method 1:
Use Angular Router with params
Page 1:
goToNewPage(){
this.router.navigate(['/identity'],{
queryParams: JSON.Stringify(data)
})
}
Page 2:
import {ActivatedRoute} from '#angular/router';
constructor(private activatedRoute: ActivatedRoute){
this.activatedRoute.queryParams.subscribe(params => {
console.log(params)
});
}
Method 2:
Create a GlobalDataProviderService.
Run Command:
ionic generate service globaldata
inside Globaldata class:
public static userObject:any;
Import this class on your both pages and initialize your variable.
Page 1:
goToNewPage(){
GlobaldataService.userObject = YourData;
this.router.navigate(['/identity'])
}
Page 2:
import this class:
inside Constructor or lifeCycle Hook.
yourVaribale = GlobaldataService.usrObject;
Method 3 for Real time Update:
Check my Other Answer: Real Time Data Update
Page 1 html code
<ion-row>
<ion-col size="12">
<ion-item>
<ion-label position="stacked">E-Mail</ion-label>
<ion-input type="email" [(ngModel)]="email"></ion-input>
</ion-item>
<ion-item>
<ion-label position="stacked">Password</ion-label>
<ion-input type="password" [(ngModel)]="password"></ion-input>
</ion-item>
<ion-item>
<ion-label>Country</ion-label>
<ion-select placeholder="Select Country" [(ngModel)]="country">
<ion-select-option value="India">India</ion-select-option>
<ion-select-option value="Usa">Usa</ion-select-option>
</ion-select>
</ion-item>
</ion-col>
<ion-col size="12" class="ion-text-center">
<ion-button (click)="goToAboutPage()" expand="block" shape="round">
Click me
</ion-button>
</ion-col>
</ion-row>
Page 1 ts code
public country: string;
public email: string;
public password: string;
constructor(public nav: NavController) {}
goToAboutPage() {
let params: any = {
country: this.country,
email: this.email,
password: this.password
}
this.nav.navigateForward('/identity', { state: params }); // params to pass object/array
}
Page 2
constructor(public router: Router){
if (router.getCurrentNavigation().extras.state) {
const params = this.router.getCurrentNavigation().extras.state;
console.log(params.email)
console.log(params.password)
console.log(params.country)
}
}

Ionic4 ngSubmit is not firing on submit

Using Ionic4 for the first time and struggling with ngSubmit not triggering the respective method in the login page. Although its always successfully hitting the LoginPage constructor and AuthService constructor. All the respective modules have been imported and there are no console errors too. What am i doing wrong ?
login.page.html:
<ion-header>
<ion-toolbar>
<ion-title>
Login
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<form (ngSubmit)="login()" [formGroup]="loginForm">
<ion-grid>
<ion-row>
<ion-col>
<ion-item>
<ion-input type="text" placeholder="Email" formControlName="email" style="width:50%;"></ion-input>
</ion-item>
</ion-col>
</ion-row>
<ion-row>
<ion-col col-3>
<ion-item>
<ion-input type="password" placeholder="Password" formControlName="password" style="width:50%;"></ion-input>
</ion-item>
</ion-col>
</ion-row>
</ion-grid>
<div padding-horizontal>
<div class="form-error">{{loginError}}</div>
</div>
<ion-grid>
<ion-row>
<ion-col>
<ion-button type="submit" [disabled]="!loginForm.valid" color="primary">Log in</ion-button>
Forgot password?
</ion-col>
</ion-row>
<ion-row>
<ion-col>
<ion-button icon-left block clear (click)="loginWithGoogle()" color="secondary">
<ion-icon name="logo-google"></ion-icon>
Log in with Google
</ion-button>
<ion-button icon-left block clear (click)="signup()" color="primary">
<ion-icon name="person-add"></ion-icon>
Sign up
</ion-button>
</ion-col>
</ion-row>
</ion-grid>
</form>
</ion-content>
login.page.ts:
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../common/services/auth.service';
import { FormGroup, FormBuilder, Validators } from '#angular/forms';
import { Router } from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
loginForm: FormGroup;
loginError: string;
constructor(private auth:AuthService,
private router:Router,
private fb: FormBuilder)
{
this.loginForm = this.fb.group({
email: ['', Validators.compose([Validators.required, Validators.email])],
password: ['', Validators.compose([Validators.required, Validators.minLength(6)])]
});
}
ngOnInit() {}
login() {
alert('login');
let data = this.loginForm.value;
if (!data.email) {
return;
}
let credentials = {
email: data.email,
password: data.password
};
this.auth.signInWithEmail(credentials)
.then(
() => this.router.navigate(['/home']),
error => this.loginError = error.message
);
}
}
login.module.ts:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule,ReactiveFormsModule } from '#angular/forms';
import { Routes, RouterModule } from '#angular/router';
import { IonicModule } from '#ionic/angular';
import { LoginPage } from './login.page';
const routes: Routes = [
{
path: '',
component: LoginPage
}
];
#NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
IonicModule,
RouterModule.forChild(routes),
],
entryComponents: [LoginPage],
declarations: [LoginPage]
})
export class LoginPageModule {}
auth.service.ts:
import { Injectable } from '#angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import AuthProvider = firebase.auth.AuthProvider;
#Injectable({
providedIn: 'root'
})
export class AuthService {
private user: firebase.User;
constructor(public afAuth: AngularFireAuth) {
afAuth.authState.subscribe(user => {
this.user = user;
});
}
signInWithEmail(credentials) {
console.log('Sign in with email');
return this.afAuth.auth.signInWithEmailAndPassword(credentials.email,
credentials.password);
}
}
ngSubmit is reloading the complete page and hence its hitting only login constructor but not the respective method. Removed (ngSubmit) on <form>, type="submit" on <ion-button>, added (click)="login()" event to <ion-button>. It started working.

Ionic2 serve shows blank screen after using formbuilder

I have a Login page. It was working fine. I changed the login form to use FormBuilder.
There is no error during build process or any reported in the developer tool. But the application shows blank screen when running with ionic serve.
Below is the code changed in login.html.
<form [formGroup]="loginForm" (ngSubmit)="login(loginForm.value)" >
<ion-row>
<ion-col>
<ion-list inset>
<ion-item>
<ion-input type="text" placeholder="Username" formControlName="username" ></ion-input>
</ion-item>
<p *ngIf="username.hasError('required') && username.touched" danger>Username is required</p>
<ion-item>
<ion-input type="password" placeholder="Password" formControlName="password"></ion-input>
</ion-item>
<p *ngIf="password.hasError('required') && password.touched" danger>Password is required</p>
</ion-list>
</ion-col>
</ion-row>
<ion-row>
<ion-col class="signup-col">
<button ion-button class="submit-btn" full type="submit" [disabled]="!loginForm.valid">Login</button>
<button ion-button class="register-btn" block clear (click)="createAccount()">Create New Account</button>
</ion-col>
</ion-row>
</form>
Below is the code changed in login.ts.
import { Component } from '#angular/core';
import { NavController, AlertController, LoadingController, Loading } from 'ionic-angular';
import { FormBuilder, FormGroup, FormControl, Validators } from '#angular/forms';
import { AuthService } from '../../providers/auth-service';
import { RegisterPage } from '../register/register';
import { HomePage } from '../home/home';
#Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class LoginPage {
loading: Loading;
registerCredentials = {username: '', password: ''};
loginForm: FormGroup;
username: FormControl;
password: FormControl;
constructor(private nav: NavController, private auth: AuthService,
private alertCtrl: AlertController, private loadingCtrl: LoadingController,
public formBuilder: FormBuilder) {
this.loginForm = formBuilder.group({
username: ['', Validators.required],
password: ['', Validators.required],
});
this.username = this.loginForm['username'];
this.password = this.loginForm['password'];
}

How do I in ionic 2 pass data from a modal with a form on, to the home page?

Hi there can anyone help out. I am new to Ionic and Angular. I am trying to create a weather app in Ionic 2.
I have created a Home page with a Click event calling an AddWeather() function.
The function opens up a modal with a form attached. I am trying to pass data from the form on the modal back to the home page an output on the screen. I have tried ngModel but can't seem to get it working correctly.
Here is my Code: (home.ts)
import { Component } from '#angular/core';
import { NavController, ModalController, NavParams } from 'ionic-angular';
import { AddPage } from '../add/add';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public weatherList = [];
constructor(public navCtrl: NavController, public modalCtrl: ModalController) {
}
addWeather() {
let addWeatherModal = this.modalCtrl.create(AddPage);
addWeatherModal.present();
}
}
(add.html)
<ion-header>
<ion-navbar color="weatherbru">
<ion-title>Modal</ion-title>
<ion-buttons end>
<button ion-button icon-only (click)="CloseModal()"><ion-icon name="close"></ion-icon></button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content padding>
<form>
<ion-item>
<ion-label stacked>City</ion-label>
<ion-input type="text" ></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>Country</ion-label>
<ion-select >
<ion-option value="us">United States</ion-option>
<ion-option value="uk">United Kingdom</ion-option>
</ion-select>
</ion-item>
<button ion-button block (click)="CloseModal()">Add Weather</button>
</form>
<div padding>
</div>
</ion-content>
(add.ts)
import { Component } from '#angular/core';
import { ModalController } from 'ionic-angular';
import { NavController, NavParams, ViewController } from 'ionic-angular';
#Component({
selector: 'page-add',
templateUrl: 'add.html'
})
export class AddPage {
constructor(public viewCtrl: ViewController, public navCtrl: NavController, public navParams: NavParams) {}
CloseModal() {
this.viewCtrl.dismiss();
}
}
In your html :
<form>
<ion-item>
<ion-label stacked>City</ion-label>
<ion-input [(ngModel)]="form.city" type="text" ></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>Country</ion-label>
<ion-select [(ngModel)]="form.country">
<ion-option value="us">United States</ion-option>
<ion-option value="uk">United Kingdom</ion-option>
</ion-select>
</ion-item>
<button ion-button block (click)="CloseModal()">Add Weather</button>
</form>
In your add.ts file :
export class AddPage {
form : any; //Declare the form object to be bound to your html
constructor(public viewCtrl: ViewController, public navCtrl: NavController, public navParams: NavParams) {}
CloseModal() {
this.viewCtrl.dismiss(this.form); //Send back the form object when closeModal is called
}
}
In your home.ts :
addWeather() {
let addWeatherModal = this.modalCtrl.create(AddPage);
addWeatherModal.present();
addWeatherModal.onDidDismiss(data=>{ //This is a listener which wil get the data passed from modal when the modal's view controller is dismissed
console.log("Data =>", data) //This will log the form entered by user in add modal.
})
}

Ionic2 JWT authentication failed with Django rest framework backend

I am building an Ionic 2 app and I am trying to use JWT to authenticate my users as shown here: https://auth0.com/blog/2016/02/18/ionic-2-authentication-how-to-secure-your-mobile-app-with-jwt/.
On clicking 'login' server sends back the token which I can see in my developer console network, however I get following error on console: (Error in build/pages/profile/profile.html:8:29 & ORIGINAL EXCEPTION: Error: JWT must have 3 parts.)Additionally I have to clear cookies everytime!
My profile.ts:
import {Page, Storage, LocalStorage} from 'ionic-angular';
import {Http, Headers} from '#angular/http';
import {FORM_DIRECTIVES} from '#angular/common';
import {JwtHelper} from 'angular2-jwt';
import {AuthService} from '../../services/auth/auth.service';
import 'rxjs/add/operator/map';
import { NavController, NavParams } from 'ionic-angular';
import { StartPage } from '../start/start.component';
#Page({
templateUrl: 'build/pages/profile/profile.html',
directives: [FORM_DIRECTIVES]
})
export class ProfilePage {
LOGIN_URL: string = " http://127.0.0.1:8000/rest-auth/login/";
SIGNUP_URL: string = "http://127.0.0.1:8000/rest-auth/registration/";
auth: AuthService;
// When the page loads, we want the Login segment to be selected
authType: string = "login";
// We need to set the content type for the server
contentHeader: Headers = new Headers({"Content-Type": "application/json"});
error: string;
jwtHelper: JwtHelper = new JwtHelper();
local: Storage = new Storage(LocalStorage);
user: string;
constructor(private http: Http, public nav:NavController) {
this.auth = AuthService;
this.local.get('profile').then(profile => {
this.user = JSON.parse(profile);
}).catch(error => {
console.log(error);
});
}
login(credentials) {
this.http.post(this.LOGIN_URL, JSON.stringify(credentials), { headers: this.contentHeader })
.map(res => res.json())
.subscribe(
data => this.authSuccess(data.id_token),
err => this.error = err
);
}
signup(credentials) {
this.http.post(this.SIGNUP_URL, JSON.stringify(credentials), { headers: this.contentHeader })
.map(res => res.json())
.subscribe(
data => this.authSuccess(data.id_token),
err => this.error = err
);
}
logout() {
this.local.remove('id_token');
this.user = null;
}
authSuccess(token) {
this.error = null;
this.local.set('id_token', token);
this.user = this.jwtHelper.decodeToken(token);
}
}
My service:
import {tokenNotExpired} from 'angular2-jwt';
export class AuthService {
constructor() {}
public static authenticated() {
return tokenNotExpired();
}
}
My profile.html:
<!-- app/profile/profile.html -->
<ion-navbar *navbar>
<button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Profile</ion-title>
</ion-navbar>
<ion-content class="login" *ngIf="!auth.authenticated()">
<div padding>
<ion-segment [(ngModel)]="authType">
<ion-segment-button value="login">
Login
</ion-segment-button>
<ion-segment-button value="signup">
Signup
</ion-segment-button>
</ion-segment>
</div>
<div [ngSwitch]="authType">
<form *ngSwitchWhen="'login'" #loginCreds="ngForm" (ngSubmit)="login(loginCreds.value)">
<ion-item>
<ion-label>Username</ion-label>
<ion-input type="text" ngControl="email"></ion-input>
</ion-item>
<ion-item>
<ion-label>Password</ion-label>
<ion-input type="password" ngControl="password"></ion-input>
</ion-item>
<div padding>
<button block type="submit">Login</button>
</div>
</form>
<form *ngSwitchWhen="'signup'" #signupCreds="ngForm" (ngSubmit)="signup(signupCreds.value)">
<ion-item>
<ion-label>Username</ion-label>
<ion-input type="text" ngControl="username"></ion-input>
</ion-item>
<ion-item>
<ion-label>Password</ion-label>
<ion-input type="password" ngControl="password"></ion-input>
</ion-item>
<div padding>
<button block type="submit">Signup</button>
</div>
</form>
</div>
<div padding>
<p *ngIf="error" class="error">{{ error._body }}</p>
</div>
</ion-content>
<ion-content>
<div *ngIf="auth.authenticated()">
<div padding>
<h1>Welcome, {{ user }}</h1>
<button block (click)="logout()">Logout</button>
</div>
</div>
</ion-content>
On successful login I would like to navigate to a specific page. What's going wrong and how can I fix this?
Also, the token I get back from my backend (I am using Django-rest-auth in my backend for authentication):