0

I'm struggling with connecting the ActivationGuard with an UserAuthenticationService, which is returning from server if the given user is logged or not. The main problem here imo is the fact, it's coming from an asynchro request.

I've got some code, made with help from one kind user on Stack. It's made with observables.

But the problem here is that I'm getting following error, when entering the protected components:

zone.js:388 Unhandled Promise rejection: Cannot read property 'do' of undefined;

My files:

ActivationGuard.ts

import {Injectable} from '@angular/core';
import {Router, CanActivate, RouterStateSnapshot, ActivatedRouteSnapshot} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {UserAuthenticationService} from './UserAuthenticationService';

@Injectable()
export class ActivationGuard implements CanActivate {

    constructor(private router: Router, private userService: UserAuthenticationService) {
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {

        return this.userService.isUserAuthenticated
            .do(success => {
                if (!success) {
                    this.router.navigate(['/']);
                }
            });
    }
}

UserAuthenticationService.ts

import {Injectable, OnInit} from '@angular/core';
import {Http} from '@angular/http';
import {Observable} from "rxjs/Observable";

@Injectable()
export class UserAuthenticationService implements OnInit {
    public isUserAuthenticated: Observable<boolean>;
    username: string = 'admin';

    constructor(private http: Http) {}


    ngOnInit(){
        this.isUserAuthenticated = this.http.get(`http://localhost/api/auth/isLogged/${this.username}`)
            .map(res => res.json())
            .share();
    }

}

Looking forward for any kind of help. If you have any questions let me know. Thank you.

Kaysh
  • 83
  • 1
  • 7

0 Answers0