Home > other >  Angular access with token
Angular access with token

Time:06-09

in angular: I have to sent [access_token_value] to each function who access to server. can I do it global?

I mean that I do not want to add it for each function ,but write it once

can i do it?

Thanks!!

CodePudding user response:

You need to use Interceptors. Read about them here in the Angular Official Documentation..

Here is an example I attach to help you understand how to create one and pass the token to it.

import {
  HttpEvent,
  HttpHandler,
  HttpHeaders,
  HttpInterceptor,
  HttpRequest,
} from '@angular/common/http'
import { Injectable } from '@angular/core'
import { Observable } from 'rxjs'

@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = localStorage.getItem('access_token') // <--- stored token to be passed to interceptor request headers
    if (token) {
      const authRequest = req.clone({
        setHeaders: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`, // <---- your token goes here
        },
      })
      return next.handle(authRequest)
    } else {
      const headers = new HttpHeaders({
        'Content-Type': 'application/json',
      })
      const cloned = req.clone({
        headers,
      })
      return next.handle(cloned)
    }
  }
}
  • Related