Angular 9-HttpInterceptor-无法读取 null 的属性长度
2020-04-07
846
我像这样使用 Angular 9 和 HttpInterceptor:
export class AppHttpInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
...
return next.handle(authReq).catch((error, caught) => {
if(error.status === 403) {
this.router.navigate(['/login']);
} else if(error.status === 400) {
console.log('Error status 400');
}
return Observable.throw(error);
}) as any;
当我最初加载应用程序时出现以下错误:
ERROR TypeError: Cannot read property 'length' of null
at http.js:168
at Array.forEach (<anonymous>)
at HttpHeaders.lazyInit (http.js:156)
at HttpHeaders.init (http.js:277)
at HttpHeaders.forEach (http.js:379)
at Observable._subscribe (http.js:2376)
at Observable._trySubscribe (Observable.js:42)
at Observable.subscribe (Observable.js:28)
at CatchOperator.call (catchError.js:16)
at Observable.subscribe (Observable.js:23)
有人知道为什么以及如何防止这个错误吗?
2个回答
尝试这样做,因为您无法从错误响应对象中获取属性状态,它将是
error.error.status
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
...
return next.handle(authReq).catch((error, caught) => {
if(error.error.status === 403) {
this.router.navigate(['/login']);
} else if(error.error.status === 400) {
console.log('Error status 400');
}
return Observable.throw(error);
}) as any;
Santosh Shinde
2020-04-07
就我而言:
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const token = this.getTokenFromLocalStorage();
const headers = new HttpHeaders(
{
'Token': token ? token : '', // validate that this not be null!
'Content-Type': 'application/json'
}
);
const REQ_INTERCEPT = req.clone({
headers: headers
});
return next.handle(REQ_INTERCEPT).pipe();
}
验证该令牌不为空!
Hector
2021-07-22