Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

5 implement canactivatechild #6

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/app/app-routing.module.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,29 @@
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './auth/auth.guard';
import { HomeComponent } from './home/home.component';
import { NonAuthenticatedComponent } from './non-authenticated/non-authenticated.component';
import { ListComponent } from './users/list/list.component';
import { UsersComponent } from './users/users.component';
import { WelcomeComponent } from './users/welcome/welcome.component';

const routes: Routes = [
{ path: '', pathMatch: 'full', redirectTo: 'home' },
{ path: 'home', component: HomeComponent },
{
path: 'users',
component: UsersComponent,
children: [
{ path: '', pathMatch: 'full', redirectTo: 'welcome' },
{ path: 'non-auth', component: NonAuthenticatedComponent },
{ path: 'welcome', component: WelcomeComponent },
{
path: '',
canActivateChild: [AuthGuard],
children: [{ path: 'list', component: ListComponent }],
},
],
},
{ path: 'non-auth', component: NonAuthenticatedComponent },
];

Expand Down
1 change: 1 addition & 0 deletions src/app/app.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
<span>{{ title }}</span>
<span class="example-spacer"> </span>
<button mat-button routerLink="home">Home</button>
<button mat-button routerLink="users">Users</button>
<button
mat-button
(click)="onLogin()"
Expand Down
2 changes: 2 additions & 0 deletions src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AngularMaterialModule } from './angular-material/angular-material.module';
import { NonAuthenticatedComponent } from './non-authenticated/non-authenticated.component';
import { HomeComponent } from './home/home.component';
import { UsersModule } from './users/users.module';

@NgModule({
declarations: [AppComponent, NonAuthenticatedComponent, HomeComponent],
Expand All @@ -15,6 +16,7 @@ import { HomeComponent } from './home/home.component';
AppRoutingModule,
BrowserModule,
BrowserAnimationsModule,
UsersModule,
],
providers: [],
bootstrap: [AppComponent],
Expand Down
16 changes: 16 additions & 0 deletions src/app/auth/auth.guard.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';

import { AuthGuard } from './auth.guard';

describe('AuthGuard', () => {
let guard: AuthGuard;

beforeEach(() => {
TestBed.configureTestingModule({});
guard = TestBed.inject(AuthGuard);
});

it('should be created', () => {
expect(guard).toBeTruthy();
});
});
36 changes: 36 additions & 0 deletions src/app/auth/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Injectable } from '@angular/core';
import {
ActivatedRoute,
CanActivateChild,
Router,
UrlTree,
} from '@angular/router';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { AuthService } from './auth.service';

@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanActivateChild {
constructor(
private readonly authService: AuthService,
private readonly router: Router,
private readonly route: ActivatedRoute
) {}
canActivateChild():
| Observable<boolean | UrlTree>
| Promise<boolean | UrlTree>
| boolean
| UrlTree {
return this.authService.isLoggedIn$.pipe(
tap((isLoggedIn) =>
isLoggedIn
? true
: this.router.navigate(['users/non-auth'], {
relativeTo: this.route,
})
)
);
}
}
2 changes: 1 addition & 1 deletion src/app/non-authenticated/non-authenticated.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Component, ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'app-non-authenticated',
template: `
<mat-card>You are not Authenticated to view that Route</mat-card>
<mat-card>You are not Authenticated to view this Route</mat-card>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
Expand Down
25 changes: 25 additions & 0 deletions src/app/users/list/list.component.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { ListComponent } from './list.component';

describe('ListComponent', () => {
let component: ListComponent;
let fixture: ComponentFixture<ListComponent>;

beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ ListComponent ]
})
.compileComponents();
});

beforeEach(() => {
fixture = TestBed.createComponent(ListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('should create', () => {
expect(component).toBeTruthy();
});
});
16 changes: 16 additions & 0 deletions src/app/users/list/list.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
selector: 'app-list',
template: `
<h3>User List</h3>
<p>
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Ipsa, eos. Totam
accusantium sit officia laborum, quisquam nemo ut perferendis voluptatum
assumenda amet suscipit laudantium sapiente sed quibusdam repudiandae
maiores consequatur.
</p>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ListComponent {}
25 changes: 25 additions & 0 deletions src/app/users/users.component.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { UsersComponent } from './users.component';

describe('UsersComponent', () => {
let component: UsersComponent;
let fixture: ComponentFixture<UsersComponent>;

beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ UsersComponent ]
})
.compileComponents();
});

beforeEach(() => {
fixture = TestBed.createComponent(UsersComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('should create', () => {
expect(component).toBeTruthy();
});
});
17 changes: 17 additions & 0 deletions src/app/users/users.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
selector: 'app-users',
template: `
<h1>Users Journey</h1>
<button mat-raised-button color="primary" routerLink="welcome">
Welcome
</button>
<button mat-raised-button color="primary" routerLink="list">
User list (Requires Authentication)
</button>
<router-outlet></router-outlet>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UsersComponent {}
15 changes: 15 additions & 0 deletions src/app/users/users.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';

import { WelcomeComponent } from './welcome/welcome.component';
import { UsersComponent } from './users.component';
import { AngularMaterialModule } from '../angular-material/angular-material.module';
import { ListComponent } from './list/list.component';

@NgModule({
declarations: [WelcomeComponent, UsersComponent, ListComponent],
exports: [WelcomeComponent, UsersComponent, ListComponent],
imports: [AngularMaterialModule, CommonModule, RouterModule],
})
export class UsersModule {}
25 changes: 25 additions & 0 deletions src/app/users/welcome/welcome.component.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { WelcomeComponent } from './welcome.component';

describe('WelcomeComponent', () => {
let component: WelcomeComponent;
let fixture: ComponentFixture<WelcomeComponent>;

beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ WelcomeComponent ]
})
.compileComponents();
});

beforeEach(() => {
fixture = TestBed.createComponent(WelcomeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('should create', () => {
expect(component).toBeTruthy();
});
});
8 changes: 8 additions & 0 deletions src/app/users/welcome/welcome.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
selector: 'app-welcome',
template: ` <h2>Welcome</h2> `,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class WelcomeComponent {}
34 changes: 20 additions & 14 deletions src/index.html
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
<!doctype html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AngularGuards</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body class="mat-typography">
<app-root></app-root>
</body>
<head>
<meta charset="utf-8" />
<title>Angular Guards - CanActivateChild</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link
href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap"
rel="stylesheet"
/>
<link
href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet"
/>
</head>
<body class="mat-typography">
<app-root></app-root>
</body>
</html>