İonic ile Üye Giriş Ekranı Tasarlama

Üye giriş işlemeleri için en basit yöntem olan firabase kullacağız. Firebase’de oturum açtıkran sonra yeni bir proje oluşturmanız gerekiyor. Projenizi oluşturduktan sonra Authentication kısmında E-posta kısmını etkin hale getirmeliyiz. Firebase de uygulamanızın api keyini kopyalayın.

Bu işlem bittikten sonra vs code ‘da terminal kısmına

npm install firebase angularfire2 --save yazarak gerekli modullerin indirilme işlemini tamamlamalıyız. İndirme işlemi bittikten sonra src/app/app.module.ts dizinine girip gerekli import’ları eklememiz gerekiyor.

import { AngularFireModule } from 'angularfire2'; import { AngularFireAuthModule } from 'angularfire2/auth'

Firebasede kopyaladığınız api keyi , src/environments/environment.ts dizinine

export const environment = {
  production: false,
  firebase: {
    apiKey: "AIzXXXXXXXXXXXXXXXWZMPN90HFrp4",
    authDomain: "test-projeXXXXXXX.firebaseapp.com",
    databaseURL: "https://test-projeXXXXXXX.firebaseio.com",
    projectId: "test-projeXXXXXXX7",
    storageBucket: "test-projeXXXXXXXX.appspot.com",
    messagingSenderId: "446XXXXXX105"
  }
 };

şeklinde kaydedin.

Şimdi giriş işlemleri için sayfamızı oluşturmamız gerekecek. Giriş sayfasını oluşturmak için teminale

ionic generate page login ionic generate page register ionic generate page dashboard ionic g service services/authentication

yazıp servisimizi ve sayfalarımızı oluşturuyoruz.

Oluşturduğumuz servisin içine aşağıdaki kodları yazıyoruz,

import { Injectable } from "@angular/core";
import * as firebase from 'firebase/app';
 
@Injectable()
export class AuthenticateService {
 
  constructor(){}
 
  registerUser(value){
   return new Promise<any>((resolve, reject) => {
     firebase.auth().createUserWithEmailAndPassword(value.email, value.password)
     .then(
       res => resolve(res),
       err => reject(err))
   })
  }
 
  loginUser(value){
   return new Promise<any>((resolve, reject) => {
     firebase.auth().signInWithEmailAndPassword(value.email, value.password)
     .then(
       res => resolve(res),
       err => reject(err))
   })
  }
 
  logoutUser(){
    return new Promise((resolve, reject) => {
      if(firebase.auth().currentUser){
        firebase.auth().signOut()
        .then(() => {
          console.log("LOG Out");
          resolve();
        }).catch((error) => {
          reject();
        });
      }
    })
  }
 
  userDetails(){
    return firebase.auth().currentUser;
  }
}


Yaptığımız değişikliklerden sonra App.Module.Ts dosyamıza gerekli eklemeleri yapıyoruz

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
 
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
 
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { environment } from 'src/environments/environment';
import { AuthenticateService } from './services/authentication.service';
import { AngularFireAuthModule } from '@angular/fire/auth';
 
import * as firebase from 'firebase';
 
firebase.initializeApp(environment.firebase);
 
@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule, 
    IonicModule.forRoot(), 
    AppRoutingModule,
    AngularFireAuthModule
  ],
  providers: [
    StatusBar,
    SplashScreen,
    AuthenticateService,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Ardından App-Routing.Module.Ts dosyamıza gerekli yönlendirmeleri yazıyoruz.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
 
const routes: Routes = [
  //{ path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: '', loadChildren: './login/login.module#LoginPageModule' },
  { path: 'register', loadChildren: './register/register.module#RegisterPageModule' },
  { path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardPageModule' }
];
 
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
 

Belirtilen dosyalara ->login.module.ts, register.module.ts ve app.module.ts ReactiveFormsModule ekliyoruz.

...
 
@NgModule({
  imports: [
    ...
    ...
    ReactiveFormsModule
    ...
    ...
  ],
  ...
})
 
...
 

:tw-1f4cc: Eklerken kütüphane importlarını güncellemeyi unutmayınız.

Login Page İşlemleri

Öncelikle login page.ts ardından html sayfasını düzenleyerek ilerleyeceğiz. Kaydol için de aynı işlemler geçerli.

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { NavController } from '@ionic/angular';
import { AuthenticateService } from '../services/authentication.service';
 
@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
 
  validations_form: FormGroup;
  errorMessage: string = '';
 
  constructor(
 
    private navCtrl: NavController,
    private authService: AuthenticateService,
    private formBuilder: FormBuilder
 
  ) { }
 
  ngOnInit() {
 
    this.validations_form = this.formBuilder.group({
      email: new FormControl('', Validators.compose([
        Validators.required,
        Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
      ])),
      password: new FormControl('', Validators.compose([
        Validators.minLength(5),
        Validators.required
      ])),
    });
  }
 
 
  validation_messages = {
    'email': [
      { type: 'required', message: 'Email is required.' },
      { type: 'pattern', message: 'Please enter a valid email.' }
    ],
    'password': [
      { type: 'required', message: 'Password is required.' },
      { type: 'minlength', message: 'Password must be at least 5 characters long.' }
    ]
  };
 
 
  loginUser(value){
    this.authService.loginUser(value)
    .then(res => {
      console.log(res);
      this.errorMessage = "";
      this.navCtrl.navigateForward('/dashboard');
    }, err => {
      this.errorMessage = err.message;
    })
  }
 
  goToRegisterPage(){
    this.navCtrl.navigateForward('/register');
  }
 
}
 

LoginPage Html

<ion-header>
  <ion-toolbar color="primary">
    <ion-title>Login</ion-title>
  </ion-toolbar>
</ion-header>
 
<ion-content padding>
  <form class="form" [formGroup]="validations_form"  (ngSubmit)="loginUser(validations_form.value)">
 
    <ion-item>
      <ion-label  position="floating" color="primary">Email</ion-label>
      <ion-input type="text" formControlName="email"></ion-input>
    </ion-item>
    <div class="validation-errors">
      <ng-container *ngFor="let validation of validation_messages.email">
        <div class="error-message" *ngIf="validations_form.get('email').hasError(validation.type) && (validations_form.get('email').dirty || validations_form.get('email').touched)">
          
        </div>
      </ng-container>
    </div>
 
    <ion-item>
      <ion-label  position="floating" color="primary">Password</ion-label>
      <ion-input type="password" formControlName="password" class="form-controll" required></ion-input>
    </ion-item>
    <div class="validation-errors">
      <ng-container *ngFor="let validation of validation_messages.password">
        <div class="error-message" *ngIf="validations_form.get('password').hasError(validation.type) && (validations_form.get('password').dirty || validations_form.get('password').touched)">
          
        </div>
      </ng-container>
    </div>
 
    <ion-button  class="submit-btn" type="submit"  [disabled]="!validations_form.valid">Log In</ion-button>
 
    <label class="error-message"></label>
  </form>
  <p class="go-to-register">
    No account yet? <a (click)="goToRegisterPage()">Create an account.</a>
  </p>
</ion-content>
 

Register Page Ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { AuthenticateService } from '../services/authentication.service';
import { NavController } from '@ionic/angular';
 
@Component({
  selector: 'app-register',
  templateUrl: './register.page.html',
  styleUrls: ['./register.page.scss'],
})
export class RegisterPage implements OnInit {
 
 
  validations_form: FormGroup;
  errorMessage: string = '';
  successMessage: string = '';
 
  validation_messages = {
   'email': [
     { type: 'required', message: 'Email is required.' },
     { type: 'pattern', message: 'Enter a valid email.' }
   ],
   'password': [
     { type: 'required', message: 'Password is required.' },
     { type: 'minlength', message: 'Password must be at least 5 characters long.' }
   ]
 };
 
  constructor(
    private navCtrl: NavController,
    private authService: AuthenticateService,
    private formBuilder: FormBuilder
  ) {}
 
  ngOnInit(){
    this.validations_form = this.formBuilder.group({
      email: new FormControl('', Validators.compose([
        Validators.required,
        Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
      ])),
      password: new FormControl('', Validators.compose([
        Validators.minLength(5),
        Validators.required
      ])),
    });
  }
 
  tryRegister(value){
    this.authService.registerUser(value)
     .then(res => {
       console.log(res);
       this.errorMessage = "";
       this.successMessage = "Your account has been created. Please log in.";
     }, err => {
       console.log(err);
       this.errorMessage = err.message;
       this.successMessage = "";
     })
  }
 
  goLoginPage(){
    this.navCtrl.navigateBack('');
  }
 
 
}

Html

<ion-header>
  <ion-toolbar color="primary">
    <ion-title>Register</ion-title>
  </ion-toolbar>
</ion-header>
 
<ion-content padding>
  <form class="form" [formGroup]="validations_form"  (ngSubmit)="tryRegister(validations_form.value)">
 
    <ion-item>
      <ion-label  position="floating" color="primary">Email</ion-label>
      <ion-input type="text" formControlName="email"></ion-input>
    </ion-item>
    <div class="validation-errors">
      <ng-container *ngFor="let validation of validation_messages.email">
        <div class="error-message" *ngIf="validations_form.get('email').hasError(validation.type) && (validations_form.get('email').dirty || validations_form.get('email').touched)">
          
        </div>
      </ng-container>
    </div>
 
    <ion-item>
      <ion-label  position="floating" color="primary">Password</ion-label>
      <ion-input type="password" formControlName="password" class="form-controll" required></ion-input>
    </ion-item>
    <div class="validation-errors">
      <ng-container *ngFor="let validation of validation_messages.password">
        <div class="error-message" *ngIf="validations_form.get('password').hasError(validation.type) && (validations_form.get('password').dirty || validations_form.get('password').touched)">
          
        </div>
      </ng-container>
    </div>
 
    
    <ion-button  class="submit-btn" type="submit"  [disabled]="!validations_form.valid">Register</ion-button>
    <label class="error-message"></label>
    <label class="success-message"></label>
  </form>
  <p class="go-to-login">Already have an account? <a (click)="goLoginPage()">Try to Log In.</a></p>
</ion-content>

Anasayfamız olan dashboard ts

import { Component, OnInit } from '@angular/core';
import { NavController, ModalController } from '@ionic/angular';
import { AuthenticateService } from '../services/authentication.service';
 
@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.page.html',
  styleUrls: ['./dashboard.page.scss'],
})
export class DashboardPage implements OnInit {
 
 
  userEmail: string;
 
  constructor(
    private navCtrl: NavController,
    private authService: AuthenticateService
  ) {}
 
  ngOnInit(){
    
    if(this.authService.userDetails()){
      this.userEmail = this.authService.userDetails().email;
    }else{
      this.navCtrl.navigateBack('');
    }
  }
 
  logout(){
    this.authService.logoutUser()
    .then(res => {
      console.log(res);
      this.navCtrl.navigateBack('');
    })
    .catch(error => {
      console.log(error);
    })
  }
}
 

Ve Html

<ion-header>
  <ion-toolbar>
    <ion-title>Dashboard</ion-title>
  </ion-toolbar>
</ion-header>
 
<ion-content padding>
 
  <ion-grid>
    <ion-row>
      <ion-col text-center>
        Welcome to Dashboard!
      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col text-center>
        Your Registered EmailID : 
      </ion-col>
    </ion-row>
  </ion-grid>  
  
  
</ion-content>
<ion-footer (click)="logout()">
  <ion-toolbar color="secondary">
    <ion-title>Log out</ion-title>
  </ion-toolbar>
</ion-footer>
 

ionic serve ile kodunuzu çalıştırıp deneyebilirsiniz.

Burada kullanılan kodlar bu adresten alınmıştır. Hesabıma girerek benim de kodlarıma bakabilirsiniz.

XOXO