1

PPl here marking it duplicate rather reading this question... The link is how to add interceptor...that I am doing already and have posted code already, question is modifying headers to be sent in interceptor

Flow of application -

Login page - user logs in- gets a token and then in all http requests need to send that token.

Working sceario

   var headers = new HttpHeaders()
        .set('Content-Type', 'application/json')
        .set('X-Token', '123'); <-- read token from storage
return this.http.post(this.url + '/' + endpoint, body, {headers: this.headers});

but problem is I have to read that token everytime which is not needed, so I cahnged code to extend HttpInterceptor

export class AddHeaderInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Clone the request to add the new header
    const clonedRequest = req.clone({ headers: req.headers.set('X-Token', 'a') });

    // Pass the cloned request instead of the original request to the next handle
    return next.handle(clonedRequest);
  }

But question is does anyone know, how can I add that token at runtime, basically after user logs in and get that token , I need to update token in that interceptor.

4
  • Not at all possible. The link is how to add interceptor...that I am doing already and have posted code above, question is modifying headers to be send in interceptor Commented Nov 27, 2017 at 11:04
  • You can store the token into service and inject that service into HttpInterceptor. Whenever token updates service will provide you the updated token. Commented Nov 27, 2017 at 11:18
  • 3
    Possible duplicate of Angular 4 - HTTP Interceptor Commented Nov 27, 2017 at 11:33
  • I'm having trouble understanding what the problem is here. If you have the token stored somewhere, why not then fetch it in your interceptor? Commented Nov 27, 2017 at 19:01

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.