Basically everything works correctly until for some reason when the url is typed the variable this.estado within the method canActivate happens to be undefined.
I think that this because the constructor does not get the observable at the correct time.
import { Component, Injectable, Inject, OnInit } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
@Injectable()
export class AuthService implements CanActivate {
myAppUrl: string;
estado: any;
constructor(private router: Router, private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) {
this.myAppUrl = baseUrl;
this.estadoSetUp(); /* If I put hear this.estado = true everything works fine */
}
public getJSON(): Observable<any> {
return this.http.get(this.myAppUrl + 'api/IsAuthenticated');
}
public estadoSetUp() {
this.getJSON().subscribe(data => {
this.estado = data.AmILoggin;
});
}
canActivate(): Observable<boolean> {
if (this.estado != true) {
this.router.navigate(['/']);
}
return this.estado;
}
}
SOLVED thanks to @sirdieter
I leave here the solution for anyone having trouble in the future:
import { Component, Injectable, Inject, OnInit } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { ReplaySubject } from 'rxjs/ReplaySubject'
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/do';
@Injectable()
export class AuthService implements CanActivate {
myAppUrl: string;
private isAuthorized = new ReplaySubject<boolean>(1);
constructor(private router: Router, private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) {
this.myAppUrl = baseUrl;
this.estadoSetUp();
}
public getJSON(): Observable<any> {
return this.http.get(this.myAppUrl + 'api/IsAuthenticated');
}
public estadoSetUp() {
this.getJSON().subscribe(data => {
this.isAuthorized.next(data.AmILoggin);
});
}
canActivate(): Observable<boolean> {
return this.isAuthorized.asObservable()
.do(auth => {
if (auth != true) {
this.router.navigate(['/']);
}
});
}
}