0

我在处理缓存查询的响应时遇到问题。

为了提高我的应用程序的性能,我研究了使用 TransferStateInterceptor 是最好的解决方案。但不幸的是,我在返回缓存的响应时遇到了一点问题。

在我的研究中,这个答案似乎是解决方案 https://stackoverflow.com/a/53492870/8747207

我也想实现这个视频中的解决方案,但是在返回缓存的响应时我总是遇到同样的问题

问题似乎是返回响应的类型,但我还没有找到有关如何解决此问题的任何有用信息。

错误具体在这一行

return of(new HttpResponse<any>({ body: cachedResponse })); // here is the type fail

错误信息是这样的:

Type 'Observable<HttpResponse>' is not assignable to type 'Observable<HttpEvent<any>>'.
  Type 'HttpResponse' is not assignable to type 'HttpEvent<any>'.
    Type 'HttpResponse' is missing the following properties from type 'HttpResponse<any>': type, clone, status, statusText, and 2 more.

在我尝试实施的两种解决方案中,就在我必须返回 HttpResponse 时它失败了。

这是我在拦截器中的代码示例。

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor} from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { TransferStateService } from '../internal/transfer-state.service';
import { HttpResponse } from 'aws-sdk';
import { tap } from 'rxjs/operators';

@Injectable()
export class TransferStateInterceptor implements HttpInterceptor {

  constructor(private transferStateService: TransferStateService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (req.method !== 'GET') {
      return next.handle(req);
    }

    const cachedResponse = this.transferStateService.getCache(req.url);
    if (cachedResponse) {
       return of(new HttpResponse<any>({ body: cachedResponse })); // here is the type fail
    }

    return next.handle(req).pipe(
      tap(event => {
        if (event instanceof HttpResponse) {
          this.transferStateService.setCache(req.url, event.body);
        }
      })
    );
   }
 }

这是我的 TransferStateService

import { isPlatformBrowser } from '@angular/common';
import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { makeStateKey, TransferState } from '@angular/platform-browser';
const transferStateCache: String[] = [];
@Injectable({
  providedIn: 'root'
})
export class TransferStateService {

  constructor(private transferState: TransferState, @Inject(PLATFORM_ID) private platformId) {}

  setCache(key: string, data: any) {
    if (!isPlatformBrowser(this.platformId)) {
      transferStateCache[key] = makeStateKey<any>(key);
      this.transferState.set(transferStateCache[key], data);
    }
  }


  getCache(key: string): any {
    if (isPlatformBrowser(this.platformId)) {
      const cachedData: any = this.transferState['store'][key];
      delete this.transferState['store'][key];
      return cachedData;
    }
  }
}

如何在拦截器中解决此问题,以便获取存储的响应?

4

1 回答 1

0

在你的TransferStateInterceptor,

import { HttpResponse } from 'aws-sdk';

虽然我相信您需要HttpResponse从“@angular/common/http”导入。

联合类型HttpEvent

import { ..., HttpResponse } from '@angular/common/http';
于 2022-02-23T02:11:35.593 回答