Home > Software design >  How to send Time zone Offset in request header in Angular?
How to send Time zone Offset in request header in Angular?

Time:10-26

I would like to send Time zone Offset in request header. But I have not find any way to do it.

My code is given below:

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';
import { SessionProvider } from './session.provider';

@Injectable({ providedIn: 'root' })
export class TokenInterceptor implements HttpInterceptor {

  constructor(private provider: SessionProvider) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const update = addHeaders(req, this.provider.session);
    const request = req.clone(update);
    return next.handle(request);
  }
}

function addHeaders(req: HttpRequest<any>, session: any): any {
  let headers = req.headers;
  if (session?.stationId) {
    headers = headers.set('wid', session.stationId);
  }
  if (session?.accessToken) {
    headers = headers.set('Authorization', 'Bearer '   session.accessToken);
  }
  return { headers };
}

I want to add Time zone Offset in addHeaders function. If someone knows how it can be done them please share your thoughts

CodePudding user response:

It can be done as follow:

function addHeaders(req: HttpRequest<any>, session: any): any {
  let headers = req.headers;
  if (session?.stationId) {
    headers = headers.set('wid', session.stationId);
  }
  if (session?.accessToken) {
    headers = headers.set('Authorization', 'Bearer '   session.accessToken);
  }
  headers = headers.set('tz-offset', getTimeZoneOffset());

  return { headers };
}

function getTimeZoneOffset(): string {
  return String(new Date().getTimezoneOffset());
}
  • Related