After working on my current code, I have encountered an issue when routing to a page with the canActivate method. I was able to retrieve authentication data from the server using the following setup
auth.guard.ts (version 1)
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private http: Http) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post('/api/authenticate', options )
.map(res => res.json())
.map((res) => {
if (res.response) {
return true;
} else {
this.router.navigate(['/register']);
return false;
}
});
}
}
I attempted to separate the code inside canActivate into auth.service.ts as shown below. However, it seems that the process does not wait for the HTTP request to complete before returning
auth.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthService {
constructor(private http: Http) { }
authenticate() :Observable<any>{
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post('/api/authenticate', { options })
.map(res => res.json())
}
}
auth.guard.ts (version 2)
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router, private http: Http) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if(this.authService.authenticate()){
return true;
}else{
this.router.navigate(['/register])
return false;
}
}
}
Can anyone point out what I am missing in this implementation?