import { Injectable } from '@angular/core'; import {ApiService} from './api.service'; import {ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot} from '@angular/router'; import {LocalStorageService} from 'angular-2-local-storage'; import {Observable} from 'rxjs'; @Injectable({ providedIn: 'root' }) export class LoginService implements CanActivate { private loggedIn; constructor( private api: ApiService, private storage: LocalStorageService ) { } login(username = '', password = '') { return new Promise(resolve => { if (username !== '') { this.storage.set('basicAuth', btoa(username + ':' + password)); } this.api.get('/authorized', (data: any, error) => { if (!error) { if (data.status === 'Authorization successful') { this.loggedIn = true; resolve(true); } else { this.loggedIn = false; this.storage.remove('basicAuth'); resolve(false); } } else { this.loggedIn = false; this.storage.remove('basicAuth'); resolve(false); } }); }); } canActivate(route: ActivatedRouteSnapshot = null, state: RouterStateSnapshot = null): Observable { return new Observable(observer => { if (this.loggedIn === undefined) { this.login().then(res => { observer.next(res as any); observer.complete(); }); } else { observer.next(this.loggedIn); observer.complete(); } }); } get isLoggedIn() { return this.loggedIn; } }