我正在按照Angular HTTP文档中的示例实现缓存拦截器。
我为caching-interceptor.ts
创建了一个新文件(在AuthInterceptor
之后,在最底部的代码),并将其包含在AppModule提供程序中。当我按原样使用下面的代码时,什么都不会发生:没有对服务器的请求(在“开发工具”的“网络”选项卡中),没有console.log输出,没有控制台错误-没什么。但是,一旦我清空了构造函数参数(即constructor() { console.log('constructor'); }
),事情就开始起作用,即,我看到constructor
已登录到控制台等。
与AuthInterceptor相同,后者最初没有构造函数。一旦我添加了具有一些随机属性的构造函数,它就会停止工作,并且没有错误。
以下《 Angular HTTP指南》中的Stackblitz包含了我用于这些示例的原始代码:https://angular.io/generated/live-examples/http/stackblitz
我的代码:
AuthInterceptor
(无构造函数)
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler
} from '@angular/common/http';
import { global } from 'src/app/global';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
console.log(`Auth heeader incoming`);
const username = global.user.name;
const authRequest = req.clone({
setHeaders: { 'X-Custom-Header': username}
});
return next.handle(authRequest);
}
}
`
CachingInterceptor
import { Injectable } from '@angular/core';
import {
HttpEvent,
HttpHeaders,
HttpRequest,
HttpResponse,
HttpInterceptor,
HttpHandler
} from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
import { RequestCacher } from 'src/app/services/request-cache.service';
@Injectable()
export class CachingInterceptor implements HttpInterceptor {
constructor(private cache: RequestCacher) {
console.log('constructor');
}
intercept(req: HttpRequest<any>, next: HttpHandler) {
console.log('intercept');
const cachedResponse = this.cache.get(req);
return cachedResponse
? of(cachedResponse)
: this.sendRequest(req, next, this.cache);
}
sendRequest(
req: HttpRequest<any>,
next: HttpHandler,
cache: RequestCacher
): Observable<HttpEvent<any>> {
// No headers allowed in npm search request
const noHeaderReq = req.clone({ headers: new HttpHeaders() });
return next.handle(noHeaderReq).pipe(
tap(event => {
// There may be other events besides the response.
if (event instanceof HttpResponse) {
cache.put(req, event); // Update the cache.
}
})
);
}
}