简体   繁体   中英

How to restrict routing from change in angular 5 application on condition base?

I am working on angular 5 application and facing a situation that I am on a component and I don't want to allow the user to switch the routing until he/she will not answer the question showing on that component. After answering the question user can switch the routing and enjoy the system.

You can achieved desired behavior using auth guard in Angular 2+.

Here is a nice article which explains how you can block certain routes based on different conditions.

Update:

you can create your router configuration like below.

import { AuthGuardService as AuthGuard } from './auth/auth-guard.service';

export const ROUTES: Routes = [
  { 
    path: 'profile',
    component: ProfileComponent,
    canActivate: [AuthGuard] 
  }
];

Then your AuthGuardService should look like this:

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuardService implements CanActivate {
  constructor(public auth: AuthService, public router: Router) {}
  canActivate(): boolean {
    if (!this.auth.isAuthenticated()) {
      this.router.navigate(['login']);
      return false;
    }
    return true;
  }
}

The point to note here is, you can inject any service to your AuthguardService (Injecting service in to another service) and construct your logic.

Guards are cool and stuff, but if you only need to disable a link until the user answers a question, you can provide an empty route with a ternary operator to disable the link.

Given that you store the answer in the answer variable :

<a [routerLink]="answer ? ['your', 'path'] : null">Continue</a>

Giving null routes cancel the routing of the application, and guards are useful when you want to prevent routing on certain modules, but for only one link ... It's overkill.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM