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

时间:2018-11-17 14:47:53

标签: angular angular-universal angular-transfer-state

我正在尝试实现内置的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。

3 个答案:

答案 0 :(得分:4)

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

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

然后,您可以将该模块放置在AppModule中TransferHttpCacheModule的导入下方:

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

这样,您的拦截器将在TransferHttpCacheInterceptor之后应用。不过,这感觉很奇怪,因为据我所知,导入首先是行中的,然后是提供程序。这样,您可以覆盖导入中的提供程序。确定要反方向吗?

答案 1 :(得分:1)

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

您的 OwnHttpInterceptor

您可以更改

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

对此

const key: StateKey<string> = makeStateKey<string>(request.url.split("/api").pop());

答案 2 :(得分:0)

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,
]