【问题标题】:Angular 9 - HttpInterceptor - Cannot read property length of nullAngular 9 - HttpInterceptor - 无法读取 null 的属性长度
【发布时间】:2021-07-23 04:37:03
【问题描述】:

我像这样使用 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)

有谁知道为什么以及如何防止这个错误?

【问题讨论】:

  • 还有其他代码吗..这似乎很正确。

标签: angular angular-http-interceptors


【解决方案1】:

尝试这样,因为您无法从错误响应对象中获取属性状态,它将是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;

【讨论】:

    【解决方案2】:

    就我而言:

      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();
    
      }
    

    验证该令牌不为空!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-27
      • 1970-01-01
      • 2023-03-11
      • 2013-03-21
      • 2015-04-06
      • 2019-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多