All files / src/app/nav authguard.service.ts

63.64% Statements 14/22
0% Branches 0/6
50% Functions 2/4
63.16% Lines 12/19
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 321x 1x 1x 1x 1x     1x   1x     3x 3x 3x     1x                         1x  
import { CanActivate, ActivatedRoute, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { NgRedux, select } from '@angular-redux/store';
import { ToastrService } from '../common/mw.common.module';
 
@Injectable()
export class AuthguardService implements CanActivate {
 
  @select(['user', 'currentUser']) currentUser$: Observable<string>;
 
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private toastr: ToastrService
  ) {}
 
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.currentUser$.map(currentUser => {
      if (currentUser) {
        return true;
      };
 
      const prompt = route.data['toastrPrompt'] || '';
      this.toastr.info( `Please log in ${prompt ? 'to access ' : ''} ${prompt}`, 'Authorisation required');
 
      this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
      return false;
    });
  }
}