填写这份《一分钟调查》,帮我们(开发组)做得更好!去填写Home

HttpContext

Http context stores arbitrary user defined values and ensures type safety without actually knowing the types. It is backed by a Map and guarantees that keys do not clash.

查看"说明"...

      
      class HttpContext {
  set<T>(token: HttpContextToken<T>, value: T): HttpContext
  get<T>(token: HttpContextToken<T>): T
  delete(token: HttpContextToken<unknown>): HttpContext
  keys(): IterableIterator<HttpContextToken<unknown>>
}
    

说明

This context is mutable and is shared between cloned requests unless explicitly specified.

Further information available in the Usage Notes...

方法

Store a value in the context. If a value is already present it will be overwritten.

      
      set<T>(token: HttpContextToken<T>, value: T): HttpContext
    
参数
token HttpContextToken

The reference to an instance of HttpContextToken.

value T

The value to store.

返回值

HttpContext: A reference to itself for easy chaining.

Retrieve the value associated with the given token.

      
      get<T>(token: HttpContextToken<T>): T
    
参数
token HttpContextToken

The reference to an instance of HttpContextToken.

返回值

T: The stored value or default if one is defined.

Delete the value associated with the given token.

      
      delete(token: HttpContextToken<unknown>): HttpContext
    
参数
token HttpContextToken

The reference to an instance of HttpContextToken.

返回值

HttpContext: A reference to itself for easy chaining.

      
      keys(): IterableIterator<HttpContextToken<unknown>>
    
参数

没有参数。

返回值

IterableIterator<HttpContextToken<unknown>>: a list of tokens currently stored in the context.

使用说明

Usage Example

      
      // inside cache.interceptors.ts
export const IS_CACHE_ENABLED = new HttpContextToken<boolean>(() => false);

export class CacheInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, delegate: HttpHandler): Observable<HttpEvent<any>> {
    if (req.context.get(IS_CACHE_ENABLED) === true) {
      return ...;
    }
    return delegate.handle(req);
  }
}

// inside a service

this.httpClient.get('/api/weather', {
  context: new HttpContext().set(IS_CACHE_ENABLED, true)
}).subscribe(...);