Cookies concent notice

This site uses cookies from Google to deliver its services and to analyze traffic.
Learn more
Skip to main content
Say hello to Angular's future home!Check out Angular.devHome
/

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.

See more...

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

Description

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

Further information is available in the Usage Notes...

Methods

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

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

The reference to an instance of HttpContextToken.

value T

The value to store.

Returns

HttpContext: A reference to itself for easy chaining.

Retrieve the value associated with the given token.

      
      get<T>(token: HttpContextToken<T>): T
    
Parameters
token HttpContextToken<T>

The reference to an instance of HttpContextToken.

Returns

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

Delete the value associated with the given token.

      
      delete(token: HttpContextToken<unknown>): HttpContext
    
Parameters
token HttpContextToken<unknown>

The reference to an instance of HttpContextToken.

Returns

HttpContext: A reference to itself for easy chaining.

Checks for existence of a given token.

      
      has(token: HttpContextToken<unknown>): boolean
    
Parameters
token HttpContextToken<unknown>

The reference to an instance of HttpContextToken.

Returns

boolean: True if the token exists, false otherwise.

      
      keys(): IterableIterator<HttpContextToken<unknown>>
    
Parameters

There are no parameters.

Returns

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

Usage notes

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(...);