Tips for implementing Angular 6 Route Authentication Guards on both Parent and Child Routes in all Routes

Exploring the Implementation of Angular 6 Route Auth Guards Across Root and Child Routes

Answer №1

Step 1: Create a guard with the file name auth.guard.ts

ng generate guard auth  

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from 
'@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
import {Router} from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private auth: AuthService,
    private myRoute: Router){
  }
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if(this.auth.isLoggedIn()){
      return true;
    }else{
      this.myRoute.navigate(["login"]);
      return false;
    }
  }
}

Step 2: Create the following pages

ng g c login  [Create login page ]
ng g c nav  [Create nav page ]
ng g c home  [Create home page ]
ng g c registration  [Create registration page ]

Step 3: Add the following contents to the App.module.ts file

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule,Router,Routes } from '@angular/router';
import { ReactiveFormsModule,FormsModule } from '@angular/forms';
import { AuthService } from './auth.service';
import { AuthGuard } from './auth.guard';

import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { NavComponent } from './nav/nav.component';
import { HomeComponent } from './home/home.component';
import { RegistrationComponent } from './registration/registration.component';

const myRoots: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full' , canActivate: 
  [AuthGuard]},
  { path: 'register', component: RegistrationComponent },
  { path: 'login', component: LoginComponent},
  { path: 'home', component: HomeComponent, canActivate: [AuthGuard]}
];

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    NavComponent,
    HomeComponent,
    RegistrationComponent
  ],
  imports: [
    BrowserModule,ReactiveFormsModule,FormsModule,
    RouterModule.forRoot(
      myRoots,
      { enableTracing: true } // <-- debugging purposes only
    )
  ],
  providers: [AuthService,AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 4: Add links in nav.component.html

<p color="primary">
  <button  routerLink="/home">Home</button>
  <button  *ngIf="!auth.isLoggedIn()" routerLink="/register">Register</button>
  <button  *ngIf="!auth.isLoggedIn()" routerLink="/login">Login</button>
  <button  *ngIf="auth.isLoggedIn()" (click)="auth.logout()">Logout</button>
</p>

Step 5: Update nav.component.ts file

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {
  constructor(public auth: AuthService) { }
  ngOnInit() {
  }
}

Step 6: Create a service page and add code in authservice.ts

ng g service auth 

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
@Injectable()
export class AuthService {
  constructor(private myRoute: Router) { }
  sendToken(token: string) {
    localStorage.setItem("LoggedInUser", token)
  }
  getToken() {
    return localStorage.getItem("LoggedInUser")
  }
  isLoggedIn() {
    return this.getToken() !== null;
  }
  logout() {
    localStorage.removeItem("LoggedInUser");
    this.myRoute.navigate(["Login"]);
  }
}

Step 7: Add content in login.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from '../auth.service';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  form;
  constructor(private fb: FormBuilder,
    private myRoute: Router,
    private auth: AuthService) {
    this.form = fb.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', Validators.required]
    });
  }
  ngOnInit() {
  }
  login() {
    if (this.form.valid) {
      this.auth.sendToken(this.form.value.email)
      this.myRoute.navigate(["home"]);
    }
  }
}

Step 8: Update login.component.html page

<form [formGroup]="form" (ngSubmit)="login()">
<div>
<input  type="email" placeholder="Email" formControlName="email" />
</div>
<div>
<input  type="password" placeholder="Password" formControlName="password" />
</div>
<button type="submit" color="primary">Login</button>
</form>

Step 9: Add below code in app.component.html

<app-nav></app-nav>
<router-outlet></router-outlet>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for eliminating duplicate values from an array

In my NodeJS code, I am currently comparing values in an array. The issue at hand is: I start with an empty array: var items = []; then proceed to insert some values into it: items[0] = {a:1, b:222}; items[1] = {a:1, b:333}; items[2] = {a:1, b:222}; ...

Communication between parent and child components in Angular 2 using objects

When you create a parent component and a child component, if you assign a primitive value (string, number, boolean) to the child component, you need to create an @Input and an @Output with EventEmitter to enable two-way communication. This process seems st ...

The initial io.emit message seems to always be delayed or lost in transmission

io.on('connection',function(socket){ console.log('connected'); socket.on('disconnect',()=>{ console.log('a user disconnected'); }); socket.on('sendMessage',function(data){ const message = data.te ...

Ways to indicate in Typescript that a value, if it exists, is not undefined

Is there a way to represent the following logic in TypeScript? type LanguageName = "javascript" | "typescript" | "java" | "csharp" type LanguageToWasmMap = { [key in LanguageName]: Exclude<LanguageName, key> ...

Display a container using Fancybox

With just a click of a button, I want to reveal a hidden div in an elegant box. Here's the code snippet that actually works: $("#btnForm").fancybox({ content: $("#divForm").html() }); However, after doing some research, it appears that this may not ...

Update the getJSON filter to only include specific results and exclude the majority

In an effort to streamline my chart to only include data for "zelcash", I am currently faced with the issue of fluctuating values causing the line graph to be inconsistent. This is because the results show zelcash with 0 as the hashrate, along with actual ...

Comparing plain objects and class instances for modeling data objects

What is the recommended approach for creating model objects in Angular using TypeScript? Is it advisable to use type annotation with object notation (where objects are plain instances of Object)? For example, let m: MyModel = { name: 'foo' } ...

In JavaScript, implement event listeners exclusively on the main container and its immediate child elements

Is there a way to target just the main container and its second child elements for an event? Specifically, targeting id="container" and all elements with class="secondChild" Currently, I have a listener attached to all elements inside ...

In order to access the localStorage from a different component, a page refresh is required as it is

UPDATE: Just to clarify, this question is NOT duplicate of how to retrieve the value from localstorage. My scenario is unique and the issue lies with Angular itself rather than localStorage. I am currently developing an Angular7 application. In one of my ...

The PHP random number generator appears to be malfunctioning when being compared to the $_POST[] variable

In this section, random numbers are generated and converted to strings. These string values are then used in the HTML. $num1 = mt_rand(1, 9); $num2 = mt_rand(1, 9); $sum = $num1 + $num2; $str1 = (string) $num1; $str2 = (string) $num2; The following code ...

The import error states that the object 'useHistory' is not available for export from the module 'react-router-dom'

Struggling with importing useHistory from 'react-router-dom' and encountering the error message: import error: 'useHistory' is not exported from 'react-router-dom'. Despite searching for solutions like Attempted import error: ...

I need help setting up the right configuration for a custom directory of Nuxt.js components. What should

<h1>Greetings everyone</h1> Currently, I'm in the process of learning how to utilize nuxt.js and have an inquiry regarding the utilization of custom directories that differ from the standard structure of a nuxt.js application. The proble ...

Tips for implementing React Browser Router within Material UI Drawer

I'm currently exploring how to implement Browser Router in React to populate the content section of a Material UI Drawer. While my code successfully links menu options to components displayed within the drawer's content section, a problem arises ...

Find the elements of <a> tags specifically without the attribute href

Currently, I am extracting the class of all <a> elements in an HTML document of a webpage using VB.net from a WinForm: Dim htmlLinks As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("a") For Each link As HtmlElement In htmlLi ...

the sequence in which a node executes a javascript function

Trying to update req.session.cart with new values for prod.quantity and prod.qtyCount in the shoppingCart field of order.save(). The issue is that orders are being saved with default quantity and qtyCount values, even though I'm setting cartProducts[ ...

Using Elasticsearch's bulk feature to set unique identifiers(_id) for documents

Whenever I attempt to insert documents into elasticsearch with a set _id, I encounter the following error: The field [_id] is considered a metadata field and cannot be included within a document. It should be utilized in the index API request parameters in ...

Selecting Content Dynamically with jQuery

I have a webpage with multiple dynamic content sections. <div id="content-1"> <div id="subcontent-1"></div> <i id="delete-1"></i> </div> . . . <div id="content-10"> <div id="subcontent-10"></d ...

Tips for transferring TimeZone Name from Angular to .NET API

Currently, the API I am working with accepts TimeZone names (such as America/Denver) as a string. In my Angular UI application, I automatically pass the browser timeZoneName to the API. However, when the API receives the string America/Denver, it interpret ...

The storybook is struggling to find the correct builder for the Angular project

I have set up a complex angular workspace with multiple projects. Within the main angular workspace project directory, I have two folders - one for the project application named eventric, and another for a library called storybook. https://i.stack.imgur.c ...

What sets canvas and webgl renderer apart in the world of three.js?

Attempting to showcase a sphere using three.js, but encountering issues when rendering with canvasRenderer due to the appearance of grey lines on the sphere. View the code here: http://jsfiddle.net/jzpSJ/ See the screenshot here: However, when rendering ...