Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 2454

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 26, 20242024-11-26T05:34:11+00:00 2024-11-26T05:34:11+00:00

Angular Dart Router – How to protect a route using RouterHook

  • 61k

In this article, you will learn how to protect a route with RouterHook and CanActivate guard. I will assume you already setup your Angular dart application and basic routing, if not you can follow the Tour of Heroes tutorial from the Angular team.

AuthService

Before we start, you must have a way to know if the user is logged in (or not). I won't cover how to implements authentication but you should have something similar to the following interface.

abstract class AuthService {   bool get isLogged;    // request API or check storage then set isLogged boolean   Future<void> checkIsLogged();    ... login, register } 
Enter fullscreen mode Exit fullscreen mode

Let's begin

We have the following routes.

/login

  • must be accessible only if the user is not logged
  • redirect to dashboard if the user already logged in

/dashboard

  • user must be logged in to access
  • redirect to login if the user not logged

The fastest way to protect a route would be to implements CanActivate class on each route.

import 'package:angular_router/angular_router.dart';  class DashboardPageComponent implements CanActivate {   final AuthService authService;    DashboardPageComponent(this.authService);    @override   Future<bool> canActivate(RouterState current, RouterState next) {     // don't activate the route if not logged     return authService.isLogged;   } } 
Enter fullscreen mode Exit fullscreen mode

But this method produces a lot of boilerplate code and is harder to maintain once your app is getting bigger. You need to implement it on each component route you want to protect.

Instead, we need to execute the isLogged check on every route and we need a way to configure which route is protected and which one is not. To do so, we will use a RouterHook that implements the canActivate method and we will use a custom config on our route definitions.

Route definitions

import 'package:angular_router/angular_router.dart';  import 'login.template.dart' as login_template; import 'dashboard.template.dart' as dashboard_template;  class RouteConfig {   final bool protected;   final bool redirectIfLoggedIn;    RouteConfig({     this.protected = false,     this.redirectIfLoggedIn = false,   }); }  final routes = [   RouteDefinition(     path: 'login',     component: login_template.LoginPageComponentNgFactory,     additionalData: RouteConfig(redirectIfLoggedIn: true),   ),   RouteDefinition(     path: 'dashboard',     component: dashboard_template.DashboardPageComponentNgFactory,     additionalData: RouteConfig(protected: true),   ), ]; 
Enter fullscreen mode Exit fullscreen mode

RouterHook

A class should extend this class and be injected along with the router to hook into route navigation. Documentations

Basically, this is a way to execute router guard each time the router is trying to navigate to a route instead on implementing it on every route component. (CanActivate, OnActivate, OnDeactivate …)

import 'package:angular/angular.dart'; import 'package:angular_router/angular_router.dart';  class AppRouterHook extends RouterHook {   final AuthService _authService;   final Injector _injector;    AppRouterHook(this._authService, this._injector);    // Lazily inject `Router` to avoid cyclic dependency.   Router _router;   Router get router => _router ??= _injector.provideType(Router);    @override   Future<bool> canActivate(     Object componentInstance,     RouterState oldState,     RouterState newState,   ) async {     // TODO: check user access     return true;   } } 
Enter fullscreen mode Exit fullscreen mode

By default, the canActivate method will let the user enter on every route.

Why use _injector.provideType(Router) ?

The Router cannot be injected in our RouterHook, because the Hook will also be injected in the angular Router and would cause cyclic dependency.

Then get the current RouteConfig and check user access.

final config = newState.routePath.additionalData; if (config is RouteConfig) {   if (config.protected && !_authService.isLogged) {     // redirect to login if not logged     router.navigate(       'login',       NavigationParams(replace: true),     );     return false;   }    if (config.redirectIfLoggedIn && _authService.isLogged) {     // redirect to dashboard if logged in     router.navigate(       'dashboard',       NavigationParams(replace: true),     );     return false;   } } 
Enter fullscreen mode Exit fullscreen mode

Initialize AuthService

You must get the user state before we initialize the router or Angular will try to navigate before we actually know if the user is logged in or not.

import 'package:angular/angular.dart'; import 'package:angular_router/angular_router.dart';  @Component(   selector: 'my-app',   styleUrls: ['app_component.css'],   template: '<router-outlet *ngIf="isReady" [routes]="routes"></router-outlet>',   directives: [     routerDirectives,     NgIf,   ], ) class AppComponent {   final AuthService authService;    bool isReady = false;    AppComponent(this.authService) {     authService.checkIsLogged().then((_) {       isReady = true;     });   } } 
Enter fullscreen mode Exit fullscreen mode

Finally inject it along with the Router and voila!

@GenerateInjector([   ClassProvider(AuthService, useClass: AuthServiceImpl),   ClassProvider(RouterHook, useClass: AppRouterHook),   routerProvidersHash, ]) final injectorFactory = template.injectorFactory$Injector; 
Enter fullscreen mode Exit fullscreen mode

Going further

You can customize the RouteConfig to follow your own rules, like protecting a route depending on User roles.

RouteConfig(allowedRoles: [Role.admin, Role.editor]); 
Enter fullscreen mode Exit fullscreen mode

Or redirect to a different path.

RouteConfig(redirectIfNotLogged: 'home'); 
Enter fullscreen mode Exit fullscreen mode

angulardartwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.