处理来自不 return canActivate() 中的布尔值的 Observable 的 HttpErrorResponse
Handle HttpErrorResponse from an Observable that doesn't return a boolean inside a canActivate()
我正在尝试创建一个 canActivate()
函数,它将 :
return false;
this.router.navigateByUrl('/login');
当 401
来自 Observable
的状态代码时,即当 HttpErrorResponse
被引发时。
============================================= =
这是我的服务:
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
我目前有此代码,当状态代码为 401
:
时失败并返回 ERROR Error: Uncaught (in promise): HttpErrorResponse
@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;
}
}));
}
}
我正在使用 angular 7.0.4.
答案是使用 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);
}));
}
}
这对我有用
returning false 什么都不做,return 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']));
})
);
}
我正在尝试创建一个 canActivate()
函数,它将 :
return false;
this.router.navigateByUrl('/login');
当 401
来自 Observable
的状态代码时,即当 HttpErrorResponse
被引发时。
============================================= =
这是我的服务:
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
我目前有此代码,当状态代码为 401
:
ERROR Error: Uncaught (in promise): HttpErrorResponse
@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;
}
}));
}
}
我正在使用 angular 7.0.4.
答案是使用 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);
}));
}
}
这对我有用 returning false 什么都不做,return 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']));
})
);
}