I use Ionic 4 to make a mobile app. I try to make authentication system and use auth guard and auth service to do this.
When I'm loggin on app, I must click twice times on login button.
As if the router took into account the guard the second time. I do not think it comes from the Promise. I do not know where it comes from.
AuthGuard
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private authService: AuthService,
) {}
canActivate(): any {
return new Promise((resolve, reject) => {
this.authService.isLoggedIn().subscribe((response) => {
resolve(response);
});
});
}
}
AuthService
isLoggedIn() {
return this.authSubject.asObservable();
}
Dashboard Route
{
path: 'dashboard',
loadChildren: './dashboard/dashboard.module#DashboardPageModule',
canActivate: [
AuthGuard,
],
},
Auth Login Template
<ion-content color="primary" padding>
<form #form="ngForm" (ngSubmit)="login(form)">
<ion-grid>
<ion-row color="primary" justify-content-center>
<ion-col align-self-center size-md="6" size-lg="5" size-xs="12">
<div text-center>
<h3>Login</h3>
</div>
<div padding>
<ion-item>
<ion-input name="email" type="email" placeholder="your#email.com" ngModel required></ion-input>
</ion-item>
<ion-item>
<ion-input name="password" type="password" placeholder="Password" ngModel required></ion-input>
</ion-item>
</div>
<div padding>
<ion-button size="large" type="submit" [disabled]="form.invalid" expand="block">Login</ion-button>
</div>
</ion-col>
</ion-row>
<ion-row>
<div text-center>
If you don't have an account, please <a routerLink="/register">register</a> first!
</div>
</ion-row>
</ion-grid>
</form>
</ion-content>
Login Page Controller
import {Component, OnInit} from '#angular/core';
import {AuthService} from '../auth.service';
import {Router} from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
constructor(
private authService: AuthService,
private router: Router,
) {
}
ngOnInit() {
}
login(form) {
this.authService.login(form.value).subscribe((res) => {
this.router.navigateByUrl('dashboard');
});
}
}
Related
Iam facing a problem in setting the password pattern as "Password must contain atleast 8 letters one lowercase and one uppercase letter one digit and one special character". I already used validators pattern but its not working.
Below is my code:
html file:
<ion-content>
<div style="margin: 30px">
<ion-title class="ion-text-center" >Register</ion-title>
<form [formGroup]="loginForm">
<ion-item>
<ion-label position="floating">First Name*</ion-label>
<ion-input formControlName="fname" type="text" ></ion-input>
</ion-item>
<div class="error-messages">
<ng-container *ngFor="let error of error_messages.fname">
<div class="error-message" *ngIf="loginForm.get('fname').hasError(error.type) && (loginForm.get('fname').dirty || loginForm.get('fname').touched)">
{{ error.message }}
</div>
</ng-container>
</div>
<ion-item>
<ion-label position="floating" >Last Name*</ion-label>
<ion-input formControlName="lname" type="text" ></ion-input>
</ion-item>
<div class="error-messages">
<ng-container *ngFor="let error of error_messages.lname">
<div class="error-message" *ngIf="loginForm.get('lname').hasError(error.type) && (loginForm.get('lname').dirty || loginForm.get('lname').touched)">
{{ error.message }}
</div>
</ng-container>
</div>
<ion-item>
<ion-label position="floating" >Email Id*</ion-label>
<ion-input formControlName="email" type="text" ></ion-input>
</ion-item>
<div class="error-messages">
<ng-container *ngFor="let error of error_messages.email">
<div class="error-message" *ngIf="loginForm.get('email').hasError(error.type) && (loginForm.get('email').dirty || loginForm.get('email').touched)">
{{ error.message }}
</div>
</ng-container>
</div>
<ion-item>
<ion-label position="floating" >Password*</ion-label>
<ion-input formControlName="password" type="password" ></ion-input>
</ion-item>
<div class="error-messages">
<ng-container *ngFor="let error of error_messages.password">
<div class="error-message" *ngIf="loginForm.get('password').hasError(error.type) && (loginForm.get('password').dirty || loginForm.get('password').touched)">
{{ error.message }}
</div>
</ng-container>
</div>
<br>
<div>
<ion-button [disabled]="!loginForm.valid" expand="full">Signup</ion-button>
</div>
.ts file:
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormBuilder, FormControl, Validators } from '#angular/forms';
#Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
loginForm: FormGroup;
error_messages = {
'fname': [
{ type: 'required', message: 'First Name is required.'},
],
'lname': [
{ type: 'required', message: 'Last Name is required.'}
],
'email': [
{ type: 'required', message: 'Email is required.'},
{ type: 'required', message: 'please enter a valid email address.'}
],
'password': [
{ type: 'required', message: 'password is required.'},
{ type: 'pattern', message: 'Password must be contain atleast 8 letters one lowercase and one uppercase letter one digit and one special character.'}
],
}
constructor(
public formBuilder: FormBuilder
) {
this.loginForm = this.formBuilder.group({
fname: new FormControl('', Validators.compose([
Validators.required
])),
lname: new FormControl('', Validators.compose([
Validators.required
])),
email: new FormControl('', Validators.compose([
Validators.required,
])),
password: new FormControl('', Validators.compose([
Validators.required,
Validators.minLength(8),
Validators.maxLength(30),
Validators.pattern('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9]+$')
])),
});
}
ngOnInit() {
}
}
Enter password should contain atleast 8 charecters, one upper case, one lower case, one numner and one special charecter.
Pleasehelp me on this.
thank you.
html .file
<ion-item>
<ion-label position="floating">
<img src="../assets/icon/key-icon.png"/>
<!-- <ion-icon name="mail" mode="ios" color="primary" "></ion-icon> -->
Password
</ion-label>
<ion-input [type]="passwordType" formControlName="password"></ion-input>
<ion-icon name="eye" [color]="passwordShown === true ? 'primary' : 'light'" slot="end" (click)="togglePassword()"></ion-icon>
</ion-item>
<ion-item no-padding lines="none" class="validator-error"
*ngIf="registration_form.controls.password.hasError('required') && registration_form.controls.password.touched">
<p>Please Enter a Password!</p>
</ion-item>
<ion-item no-padding lines="none" class="validator-error"
*ngIf="registration_form.controls.password.hasError('minlength') && registration_form.controls.password.touched">
<p>The password needs at least 8 characters.</p>
</ion-item>
<ion-item no-padding lines="none" class="validator-error"
*ngIf="registration_form.controls.password.hasError('pattern') && registration_form.controls.password.touched">
<p>Please Enter One Upper Case and One Lower Case, One Spacial Characters and One Number</p>
</ion-item>
ts.file
password: [null, Validators.compose([
Validators.required,
Validators.pattern('(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$#$!%*?&])[A-Za-z\d$#$!%*?&].{7,}'),
Validators.minLength(8)
])]
Just add the below in the validators pattern
Validators.pattern('(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$#$!%*?&])[A-Za-z\d$#$!%*?&].{7,}'),
Iam newbie to ionic and creating a basic mobile app after learning ionic online.
I had created a customer details form page where customers need to enter their details like, name, gender, dob, city etc.
Instead of manually entering the entering the details, I want to put QR Scanner in the page so that when Aadhaar or any other barcode details saver QR code gets scanned the customer details needs to gets filled automatically.
Below is the code
<ion-content>
<ion-item>
<ion-label position="floating" >Full Name</ion-label>
<ion-input type="text" ></ion-input>
</ion-item>
<ion-item>
<ion-label position="floating" >DOB</ion-label>
<ion-input type="text" ></ion-input>
</ion-item>
<ion-item>
<ion-label position="floating" >Gender</ion-label>
<ion-input type="text" ></ion-input>
</ion-item>
<ion-item>
<ion-label position="floating" >Address</ion-label>
<ion-input type="text" ></ion-input>
</ion-item>
<ion-item>
<ion-label position="floating" >State</ion-label>
<ion-input type="text" ></ion-input>
</ion-item>
<ion-item>
<ion-label position="floating" >District</ion-label>
<ion-input type="text" ></ion-input>
</ion-item>
<ion-item>
<ion-label position="floating" >City</ion-label>
<ion-input type="text" ></ion-input>
</ion-item>
<ion-item>
<ion-label position="floating" >Postal Code</ion-label>
<ion-input type="text" ></ion-input>
</ion-item>
I tried installing the ionic qr scanner plugins
ionic cordova plugin add cordova-plugin-qrscanner
npm install #ionic-native/qr-scanner
But no idea how to proceed further. Please help me on this, i got struct on this from last 10 days
Thank you
Have a look at my code for scanning QR codes (Ionic 4)
To be honest, I like the barcode-scanner way more than the qr code scanner and basically the outcome is the same.
https://ionicframework.com/docs/native/barcode-scanner
import { Component } from '#angular/core';
import { Router, NavigationEnd } from '#angular/router';
import { Platform, AlertController } from '#ionic/angular';
import { DatabaseService} from '../../providers/database/database.service';
import { BarcodeScanner } from '#ionic-native/barcode-scanner/ngx';
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
current:any;
constructor(
private platform: Platform,
private router: Router,
public db: DatabaseService,
public barcodeScanner: BarcodeScanner,
private alertController: AlertController
)
{}
scan()
{
this.barcodeScanner.scan().then(barcodeData => {
if(barcodeData.cancelled)
{
return
}
this.db.checkQRCode(barcodeData.text)
.then(doc => {
})
}).catch(err => {
console.log('Error', err);
});
}
}
Here the video i am following this video, I did same as video, but still showing me error undefined value. anyone had idea what to do. Please help me and i am using ionic 3,
Here the video i am following this video, I did same as video, but still showing me error undefined value. anyone had idea what to do. Please help me and i am using ionic 3,
home.html
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item>
<ion-label floating>Username</ion-label>
<ion-input type="text" name="username" ></ion-input>
</ion-item>
<ion-item>
<ion-label floating>Password</ion-label>
<ion-input type="password" name="password"></ion-input>
</ion-item>
</ion-list>
<div padding>
<button ion-button color="primary" (click)="signIn()" block>Sign In</button>
</div>
</ion-content>
home.ts
import { Component, ViewChild } from '#angular/core';
import { NavController, AlertController } from 'ionic-angular';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
#ViewChild('username') uname;
#ViewChild('passwoed') password;
constructor(public navCtrl: NavController, public alertCtrl:
AlertController ) {
}
signIn() {
console.log(this.uname.value, this.password.value)
if(this.uname.value == "admin" && this.password.value == "admin") {
let alert = this.alertCtrl.create({
title: 'Login Successfull!',
subTitle: 'You are logged in!',
buttons: ['OK']
});
alert.present();
}
}
}
You got mistake on home.html, i resolve this.
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item>
<ion-label floating>Username</ion-label>
<ion-input type="text" #username ></ion-input>
</ion-item>
<ion-item>
<ion-label floating>Password</ion-label>
<ion-input type="password" #password></ion-input>
</ion-item>
</ion-list>
<div padding>
<button ion-button color="primary" (click)="signIn()" block>Sign In</button>
</div>
</ion-content>
I am developing a SIgnup page in ionic 3 and the no of fields are 10.
SO I am using a p tag to show validation and when the user hits submit I want to take him all the way up to the start of the page which has my header and all.How can I achieve this?I have tried everything.
Below is my code:
<ion-content padding class="label-cl green-bg acct-sct item-row" style="position:fixed">
<h2 class="center-col">Create An Account</h2>
<form #f="ngForm" (ngSubmit)="signUp(f)">
<ion-item>
<ion-label floating>Username</ion-label>
<ion-input type="text" name="name" ngModel required></ion-input>
</ion-item>
<p style="color:red;text-align: left" *ngIf="usernameError">Invalid Username</p>
<ion-item>
<ion-label floating>Email</ion-label>
<ion-input type="email" name="email" ngModel required></ion-input>
</ion-item>
<p style="color:red;text-align: left" *ngIf="emailError">Invalid E-mail</p>
<ion-item>
<ion-label floating>Password</ion-label>
<ion-input type="Password" name="password" ngModel required></ion-input>
</ion-item>
<p style="color:red;text-align: left" *ngIf="passwordLengthError">Invalid Password</p>
<ion-item>
<ion-label floating>Confirm Password</ion-label>
<ion-input type="Password" name="confirm_password" ngModel required></ion-input>
</ion-item>
<div class="button-inline">
<button ion-button class="yellow-cl" [disabled]="!f.valid">Submit</button>
</div>
</form>
</ion-content>
It has more fields but I am showing only these just for the sake of clarity.
Thanks in advance.
Add the below code to your .ts file
import { Component, ViewChild } from '#angular/core';
import { Content } from 'ionic-angular';
#Component({...})
export class SignUpPage{
#ViewChild(Content) content: Content;
signUp() {
this.content.scrollToTop();
}
}
We used Angular's #ViewChild annotation to get a reference to the ionic content component which has the method scrollToTop().
Find more details in the Official docs
I have an ionic app with side-menu. My requirement is to have a Login Page before side-menu page.
By clicking on login button first time application gets reload, on clicking second time navigates to the side Menu page.
Here is my code
app.ts
config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'loginCtrl'
})
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
})
.state('app.home', {
url: '/home',
cache: true,
views: {
'menuContent': {
templateUrl: 'templates/home.html',
controller: "homeController"
}
}
})
<ion-view>
<ion-content>
<div class="login-main-heading">
<h3 class="all-elements-center login-heading">Welcome</h3>
<div class="form-elements responsive-sm">
<h5 class="all-elements-center login-heading">Login</h5>
<form action="">
<div class="list list-inset">
<label class="item item-input">
<i class="icon ion-person placeholder-icon"></i>
<input type="text" placeholder="User Name">
</label>
<label class="item item-input">
<i class="icon ion-lock-combination placeholder-icon"></i>
<input type="password" placeholder="Password">
</label>
<div class="responsive-sm">
<button class="button button-large button-assertive button-login">
Login
</button>
<button class="button button-large button-assertive button-signup">
Sign Up
</button>
</div>
<div>
<button class="button button-block button-positive button-facebook- login" ng-click="login()">
Login
</button>
</div>
</div>
</form>
</div>
</ion-content>
</ion-view>
login-controller.js
angular.module('starter')
.controller('loginCtrl', function ($scope, $state,$ionicSideMenuDelegate) {
$scope.login = function () {
$state.go('app.home');
}
});
app-controller.js
angular.module('starter.controllers', [])
.controller('AppCtrl', function ($scope, $state) {
});