Rahul Pamnani
Rahul Pamnani

Reputation: 1435

Redirect the user when the user visits the particular route in Ionic 4

I am working in my Ionic 4 App and I am working on Login system and When the user will login, it will redirect to the page where the user can check the challenges for the user and when the user is not login and if it try to visit the page then it should redirect to the other page.

This is my userlogin.ts:

async UserLoginDetails($soctype, $socid) {
    const loading = await this.loadingController.create({
      message: 'Please Wait',
      duration: 1100,
      translucent: true,
    });
    await loading.present();
    const userdetailslogin = {
      email: this.userlogindet.value.email,
      password: this.userlogindet.value.password,
      social_type: $soctype,
      social_id: $socid,
    };
    this.chakapi.loginUser(userdetailslogin, 'userLogin').subscribe((data) => {
      console.log(data);
      if (data) {
        this.responseEdit = data;
        if (this.responseEdit.status === 'success') {
          console.log(this.responseEdit.data.id);
          this.storage.set('ID', this.responseEdit.data.id);
          this.presentAlertConfirm('Login Successful', 1);
        } else {
          this.presentAlertConfirm('Either You are not registered Or not approved user.', 0);
        }
      }
    });
    return await loading.onDidDismiss();
}

async presentAlertConfirm($messge, $para) {
    const alert = await this.alertController.create({
      message: $messge,
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {
            // console.log('Confirm Cancel: blah');
            if ($para === 1) {
              this.modalController.dismiss();
              this.router.navigate(['/tabs/tab2']);
            }
          }
        }]
    });
    await alert.present();
}

When the user will login, its user Id will get store in the storage.

This is my tabs.router.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { TabsPage } from './tabs.page';

const routes: Routes = [
  {
    path: 'tabs',
    component: TabsPage,
    children: [
      {
        path: 'tab1',
        children: [
          {
            path: '',
            loadChildren: '../tab1/tab1.module#Tab1PageModule'
          }
        ]
      },
      {
        path: 'tab2',
        children: [
          {
            path: '',
            loadChildren: '../tab2/tab2.module#Tab2PageModule'
          }
        ]
      },
      {
        path: 'tab4',
        children: [
          {
            path: '',
            loadChildren: '../login/login.module#LoginPageModule'
          }
        ]
      },
      {
        path: 'tab3',
        children: [
          {
            path: '',
            loadChildren: '../tab3/tab3.module#Tab3PageModule'
          }
        ]
      },
      {
        path: '',
        redirectTo: '/tabs/tab1',
        pathMatch: 'full'
      }
    ]
  },
  {
    path: '',
    redirectTo: '/tabs/tab1',
    pathMatch: 'full'
  }
];

@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ],
  exports: [RouterModule]
})
export class TabsPageRoutingModule {}

I want that when the user is not login and it will try to visit the tab2 route, it should redirect to some other page.

Should I use the guard service or I am doing this correctly. I am storing the User Id in the storage because I want to use it multiple times.

Any suggestion or help is much appreciated. Please help me with the code because I am working on a project and I want to complete it on time.

Any help is much appreciated.

Upvotes: 0

Views: 1073

Answers (1)

Jason White
Jason White

Reputation: 5843

You can use a guard to accomplish this. The guard will determine if the user is logged in or not. If not, the user will be redirected to another route (login page or wherever you want them to land).


authentication.guard.ts

@Injectable({
  providedIn: 'root'
})
export class AuthenticationGuard implements CanActivate {

  constructor(private _router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    let isLoggedIn: boolean = false;

    // NOTE: Do your logic here to determine if the user is logged in or not.

    // return true if use is authenticated
    if(isLoggedIn) return true;

    // else redirect the user to another route and return false.
    this._router.navigate(['login']);
    return false;
  }
}

tabs.router.module.ts

const routes: Routes = [
  {
    path: 'tabs',
    component: TabsPage,
    children: [
      ...
      {
        path: 'tab2',
        canActivate: [AuthenticationGuard],
        children: [
          {
            path: '',
            loadChildren: '../tab2/tab2.module#Tab2PageModule'
          }
        ]
      },
      ...
    ]
  }
  ...
];

Angular guards are used like filters. You can add an array of guards/filters to your route which all must be satisfied in order to access that route (acts as a chain). In your routing array add a canActivate attribute to the route you want filtered. In the above example I added the AuthenticationGuard to the tab2 route which will only run when the user tries to access tab2 or any of it's children. You can place canActivate at the root of the routes (tabs) to filter all children of tabs route (will filter tab1, tab2, etc).

https://angular.io/api/router/CanActivate

https://angular.io/guide/router

Upvotes: 1

Related Questions