Angular 9:如何使用 HttpInterceptor 显示请求的堆栈跟踪?

Sim*_*gro 5 javascript angular-http-interceptors angular

我有一个HttpInterceptor,出于开发目的,我想打印发出请求的函数的堆栈跟踪:

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class HttpInterceptorService implements HttpInterceptor {

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log('Who has made this request?', new Error().stack);
    return next.handle(request);
  }
}
Run Code Online (Sandbox Code Playgroud)

控制台日志的输出为:

at HttpInterceptorService.intercept (:4200/main.js:1344) [angular]
    at HttpInterceptorHandler.handle (:4200/vendor.js:30718) [angular]
    at HttpXsrfInterceptor.intercept (:4200/vendor.js:31484) [angular]
    at HttpInterceptorHandler.handle (:4200/vendor.js:30718) [angular]
    at HttpInterceptingHandler.handle (:4200/vendor.js:31549) [angular]
    at MergeMapSubscriber.project (:4200/vendor.js:30457) [angular]
    at MergeMapSubscriber._tryNext (:4200/vendor.js:112207) [angular]
    at MergeMapSubscriber._next (:4200/vendor.js:112197) [angular]
    at MergeMapSubscriber.next (:4200/vendor.js:107493) [angular]
    at Observable._subscribe (:4200/vendor.js:116912) [angular]
    at Observable._trySubscribe (:4200/vendor.js:106949) [angular]
    at Observable.subscribe (:4200/vendor.js:106935) [angular]
    at MergeMapOperator.call (:4200/vendor.js:112182) [angular]
    at Observable.subscribe (:4200/vendor.js:106930) [angular]
Run Code Online (Sandbox Code Playgroud)

输出不显示有关哪个组件或服务发出请求的任何有用信息。

有一些提示可以显示查找服务和组件的堆栈跟踪的有用信息吗?

Pie*_*Duc 3

拦截器内部的痕迹已经混乱了。您还可以考虑使用自定义HttpClient. 但这是未经测试的代码。因此,如果您删除拦截器提供程序并将其替换为:

{ provide: HttpClient, useClass: TraceHttpClient }

Run Code Online (Sandbox Code Playgroud)

你的TraceHttpClient看起来像这样:

@Injectable()
export class TraceHttpClient extends HttpClient {
  constructor(handler: HttpHandler) {
     super(handler);
  }

  request(...args: [ any ]): Observable<any> {
    console.trace('Who has made this request?');

    return super.request(...args);
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看工作版本。您可以看到具有不同按钮方法调用的堆栈跟踪。不过,您应该打开浏览器控制台,因为 stackblitz 控制台不显示日志console.trace

HttpClient对每个 GET/POST/etc的调用......request因此,只需扩展该方法,并在那里放置跟踪,然后委托回基HttpClient类就足够了