Estoy tratando de implementar authGuard para mis enrutadores. pero cuando interfiero con los códigos de error, la aplicación se rompe. No sé cómo abordarlo. asistencia necesaria.
Mi AuthGuard
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean { return this._auth.validate() .map((isValidated) => { if (isValidated && localStorage.getItem('authToken') && this.checkCookie()) { return true; } this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } }); return false; }); }Mi servicio de autenticación
@Injectable() export class AuthService { loginStatus; constructor(private http: Http, private _apiEndPoint: ApiEndPoint, private router: Router) { } validate() { return this.http.get(this._apiEndPoint.validate) .map( (response: Response) => { const result = response.json(); // check authentication status from response if (result.authenticated) { return true; } else { return false; } }) .catch(error => Observable.throw(error)); } }Recibo este error, No capturado (en promesa): Respuesta con estado: 401 No autorizado para URL.
y cuando recibo ese error, mi página se queda en blanco.
Lo arreglé devolviendo observable de falso
return this._auth.validate() .map((isValidated) => { if (isValidated && localStorage.getItem('authToken') && this.checkCookie()) { return true; } }).catch(() => { this.router.navigate(['/login']); return Observable.of(false); });necesita usar una captura, y la captura tiene que devolver un observable.
validate() { return this.http.get(this._apiEndPoint.validate) .map( (response: Response) => { const result = response.json(); // check authentication status from response return result.authenticated; }) .catch(error => Observable.throw(error)); // If you want to throw nothing, then return Observable.empty() }