Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { AngularFireModule } from '@angular/fire';
- import { AngularFireAuthModule } from '@angular/fire/auth';
- import { AngularFirestoreModule } from '@angular/fire/firestore';
- @NgModule({
- imports: [
- BrowserModule.withServerTransition({ appId: 'serverApp' }),
- // Firebase
- AngularFireModule.initializeApp(environment.firebase),
- AngularFirestoreModule,
- AngularFireAuthModule,
- // App
- AppRoutingModule
- ],
- declarations: [
- AppComponent
- ],
- bootstrap: [AppComponent]
- })
- export class AppModule {}
- import { Injectable } from '@angular/core';
- import { CanActivate, CanActivateChild, CanLoad } from '@angular/router';
- import * as firebase from 'firebase/app';
- @Injectable({
- providedIn: 'root'
- })
- export class AuthGuard implements CanActivate, CanActivateChild, CanLoad {
- /** @ignore */
- constructor() {}
- canLoad(): boolean {
- return this.performCheck();
- }
- canActivate(): boolean {
- return this.performCheck();
- }
- canActivateChild(): boolean {
- return this.performCheck();
- }
- private performCheck() {
- return !!firebase.auth().currentUser;
- }
- }
- export const Routes = [
- {
- path: '',
- pathMatch: 'full',
- redirectTo: 'hello'
- },
- {
- path: 'hello',
- component: HelloComponent,
- canActivate: [AuthGuard]
- }
- ];
- import { Injectable } from '@angular/core';
- import { CanActivate, CanActivateChild, CanLoad } from '@angular/router';
- import { AngularFireAuth } from '@angular/fire/auth'; // instead of firebase
- import { Observable } from 'rxjs';
- import { take, map } from 'rxjs/operators'
- @Injectable({
- providedIn: 'root'
- })
- export class AuthGuard implements CanActivate, CanActivateChild, CanLoad {
- /** @ignore */
- constructor(private auth: AngularFireAuth) {}
- canLoad(): Observable<boolean> {
- return this.performCheck();
- }
- canActivate(): Observable<boolean> {
- return this.performCheck();
- }
- canActivateChild(): Observable<boolean> {
- return this.performCheck();
- }
- private performCheck(): Observable<boolean> {
- return this.auth.user.pipe(map((user) => {
- if (user) {
- // user is logged in
- return true;
- }
- // user is not logged in
- return false;
- }),
- take(1));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement