我正在尝试创建一个canActivate()
函数,该函数将:
return false;
this.router.navigateByUrl('/login');
从401
发出状态代码Observable
时,即HttpErrorResponse
发出时。
============================================= < / p>
这是我的服务:
currentUser(token): Observable<any> {
const url = `${this.BACKEND_URL}/status`;
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
})
};
return this.http.post(url, {'token': token}, httpOptions);
}
响应数据是一个Json Blob,并且可以是401
或200
状态代码,这是Python代码:
post_data = request.get_json()
post_token = post_data.get('token')
resp = User.decode_auth_token(post_token)
if not isinstance(resp, str):
user = User.query.filter_by(id=resp).first()
response_object = {
'status': 'success',
'data': {
'user_id': user.id,
'email': user.email.lower(),
'first_name': user.first_name,
'last_name': user.last_name,
'admin': user.admin,
'registered_on': user.registered_on
}
}
return make_response(jsonify(response_object)), 200
response_object = {
'status': 'fail',
'message': resp
}
return make_response(jsonify(response_object)), 401
我目前有这样的代码,当状态代码为ERROR Error: Uncaught (in promise): HttpErrorResponse
时,代码失败,401
:
@Injectable()
export class EnsureAuthenticated implements CanActivate {
constructor(private auth: AuthService, private router: Router) {}
canActivate(): Observable<boolean> {
console.log('AUTH');
return this.auth.currentUser(localStorage.getItem('token')).pipe(map(suc => {
if (suc.status = 'success') {
return true;
} else {
this.router.navigateByUrl('/login');
return false;
}
}));
}
}
我正在使用角度7.0.4。
答案 0 :(得分:0)
答案是使用catchError
捕获错误:
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';
import {Observable, of} from 'rxjs';
import {catchError, map} from 'rxjs/operators';
import {HttpErrorResponse} from '@angular/common/http';
@Injectable()
export class EnsureAuthenticated implements CanActivate {
constructor(private auth: AuthService, private router: Router) {}
canActivate(): Observable<boolean> {
return this.auth.currentUser(localStorage.getItem('token')).pipe(map(suc => {
if (suc.status = 'success') {
return true;
} else {
this.router.navigateByUrl('/login');
return false;
}
}), catchError((err: HttpErrorResponse) => {
this.router.navigateByUrl('/login');
return of(false);
}));
}
}
答案 1 :(得分:0)
这对我有用 不要返回什么都不做的 false,而是直接返回 UrlTree 以导航到您想去的地方。
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
):
| Observable<boolean | UrlTree>
| Promise<boolean | UrlTree>
| boolean
| UrlTree {
return this.accountClientService.isLoggedIn().pipe(
map((responseData: ResponseService<boolean>) => {
if (responseData.model) {
return responseData.model;
}
return this.router.createUrlTree(['/signin']);
}),
catchError((err) => {
return of(this.router.createUrlTree(['/signin']));
})
);
}