使用相对 URL 时如何使用 HTTP 传输状态

问题描述 投票:0回答:3

我正在尝试实现内置的 TransferHttpCacheModule 以消除重复请求。我在我的应用程序中使用这个拦截器:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authService = this.injector.get(AuthenticationService);
    const url = `${this.request ? this.request.protocol + '://' + this.request.get('host') : ''}${environment.baseBackendUrl}${req.url}`

    let headers = new HttpHeaders();

    if (this.request) {
      // Server side: forward the cookies
      const cookies = this.request.cookies;
      const cookiesArray = [];
      for (const name in cookies) {
        if (cookies.hasOwnProperty(name)) {
          cookiesArray.push(`${name}=${cookies[name]}`);
        }
      }
      headers = headers.append('Cookie', cookiesArray.join('; '));
    }

    headers = headers.append('Content-Type', 'application/json');

    const finalReq: HttpRequest<any> = req.clone({ url, headers });
    ...

它为客户端启用相对 URL,为服务器端启用完整 URL,因为服务器不知道自己的 URL。

问题在于

TransferHttpCacheModule
使用基于方法、URL 和参数的密钥,并且服务器 URL 与客户端 URL 不匹配。

有没有办法强制

TransferHttpCacheInterceptor
在我自己的拦截器之前执行?我想避免在客户端强制使用完整的 URL。

angular angular-universal angular-transfer-state
3个回答
6
投票

您可以将拦截器放置在其自己的模块中:

@NgModule({
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: MyOwnInterceptor, multi: true }
  ]
})
export class MyOwnInterceptorModule {}

然后您可以将此模块放置在 AppModule 内

TransferHttpCacheModule
的导入下方:

@NgModule({
  imports: [
    // ...
    TransferHttpCacheModule,
    MyOwnInterceptorModule
  ],
  // ...
})
export class AppModule {}

这样你的拦截器将在

TransferHttpCacheInterceptor
之后应用。但这感觉很奇怪,因为据我所知,导入是排在第一位的,然后是提供者。这样您就可以覆盖导入中的提供程序。你确定你不想反过来吗?


1
投票

我在 angularspree

中的 Angular 通用支持也遇到了同样的问题

我遵循了这些方法:

=> 创建一个 TransferStateService,它公开设置和获取缓存数据的函数。

import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { TransferState, makeStateKey } from '@angular/platform-browser';
import { isPlatformBrowser } from '@angular/common';

/**
 * Keep caches (makeStateKey) into it in each `setCache` function call
 * @type {any[]}
 */
const transferStateCache: String[] = [];

@Injectable()
export class TransferStateService {
  constructor(private transferState: TransferState,
    @Inject(PLATFORM_ID) private platformId: Object,
    // @Inject(APP_ID) private _appId: string
  ) {
  }

  /**
   * Set cache only when it's running on server
   * @param {string} key
   * @param data Data to store to cache
   */
  setCache(key: string, data: any) {
    if (!isPlatformBrowser(this.platformId)) {
      transferStateCache[key] = makeStateKey<any>(key);
      this.transferState.set(transferStateCache[key], data);
    }
  }


  /**
   * Returns stored cache only when it's running on browser
   * @param {string} key
   * @returns {any} cachedData
   */
  getCache(key: string): any {
    if (isPlatformBrowser(this.platformId)) {
      const cachedData: any = this.transferState['store'][key];
      /**
       * Delete the cache to request the data from network next time which is the
       * user's expected behavior
       */
      delete this.transferState['store'][key];
      return cachedData;
    }
  }
}

=> 创建一个TransferStateInterceptor来拦截服务器端平台的请求。

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

@Injectable()
export class TransferStateInterceptor implements HttpInterceptor {
  constructor(private transferStateService: TransferStateService) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    /**
     * Skip this interceptor if the request method isn't GET.
     */
    if (req.method !== 'GET') {
      return next.handle(req);
    }

    const cachedResponse = this.transferStateService.getCache(req.url);
    if (cachedResponse) {
      // A cached response exists which means server set it before. Serve it instead of forwarding
      // the request to the next handler.
      return of(new HttpResponse<any>({ body: cachedResponse }));
    }

    /**
     * No cached response exists. Go to the network, and cache
     * the response when it arrives.
     */
    return next.handle(req).pipe(
      tap(event => {
        if (event instanceof HttpResponse) {
          this.transferStateService.setCache(req.url, event.body);
        }
      })
    );
  }
}

=> 将其添加到您的 module 中的提供程序部分。

providers: [
  {provide: HTTP_INTERCEPTORS, useClass: TransferStateInterceptor, multi: true},
  TransferStateService,
]

1
投票

我遇到了同样的问题,并通过删除 makeStateKey 中的主机解决了它。

你的自己的HttpInterceptor

你可以改变这个

const key: StateKey<string> = makeStateKey<string>(request.url);

到此

const key: StateKey<string> = makeStateKey<string>(request.url.split("/api").pop());
© www.soinside.com 2019 - 2024. All rights reserved.