Skip to content

Commit

Permalink
fixes Implement CanActivate guard #3
Browse files Browse the repository at this point in the history
  • Loading branch information
akshay3001 committed Apr 1, 2022
1 parent 76eb4c8 commit c011299
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 0 deletions.
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();
});
});
27 changes: 27 additions & 0 deletions src/app/auth/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Injectable } from '@angular/core';
import { CanActivate, 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 CanActivate {
constructor(
private readonly authService: AuthService,
private readonly router: Router
) {}

canActivate():
| Observable<boolean | UrlTree>
| Promise<boolean | UrlTree>
| boolean
| UrlTree {
return this.authService.isLoggedIn$.pipe(
tap((isLoggedIn) =>
isLoggedIn ? true : this.router.navigate(['non-auth'])
)
);
}
}
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 { ChangeDetectionStrategy, Component } from '@angular/core';

@Component({
selector: 'app-users',
template: `
<mat-card>
<h2>Users</h2>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Adipisci hic
libero ratione soluta consequuntur quam illum exercitationem aut maiores
voluptatem minus quisquam in, eos, et aperiam error ducimus cum officia?
</p>
</mat-card>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UsersComponent {}

0 comments on commit c011299

Please sign in to comment.