Open sidebar
import { Injectable, Output, EventEmitter } from "@angular/core"; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from "@angular/router"; import { Observable } from "rxjs/Rx"; import { AuthService } from "./auth.service"; import { StorageService } from "../shared/storage.service"; import { User } from "../shared/user.interface"; @Injectable() export class AuthGuard implements CanActivate { @Output() user = new EventEmitter<User>(); @Output() isAuthenticated = new EventEmitter<boolean>(); constructor(private authService: AuthService, private router: Router, private storageService: StorageService ) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean { this.authService.getAuthenticatedUser().subscribe( (response) => { if (state.url !== '/login' && !response.user) { this.authService.logout(); return false; } this.storageService.write('token', response.token); this.storageService.write('user', response.user); } ) this.user.emit(this.storageService.read<User>('user')); this.isAuthenticated.emit(true); return true; } } // Listening Component Seciton import { Component, OnInit, Input } from '@angular/core'; import { AuthService } from '../auth/auth.service'; import { SiteService } from '../shared/site.service'; import { StorageService } from '../shared/storage.service'; import { User } from '../shared/user.interface'; @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.css'] }) export class HeaderComponent implements OnInit { @Input() isAuthenticated; //Does not seem to work @Input() user: User; //Does not seem to work builder_logo = null; constructor(private authService: AuthService, private siteService: SiteService, private storageService: StorageService) { } ngOnInit() { this.builder_logo = this.siteService.getBuilderLogo(); } onLogout() { this.isAuthenticated = false; this.authService.logout(); } }
Close sidebar
Back
Please note that all pasted data is publicly available.
X (fomerly Twitter)
GitHub
Use setting
Back
Please note that all pasted data is publicly available.
X (fomerly Twitter)
GitHub
Use setting