0

Working in Angular 4 application. Created http interceptor for sending request to the api.

@Injectable()
export class HttpRequestInteceptor implements HttpInterceptor {
    loginUserName = "";
    constructor(private router: ActivatedRoute) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {


        if (environment.Authentication == 1) {           
            // add a custom header


            const newRequest = req.clone({headers: req.headers.set('userName', '11111')});
            return next.handle(newRequest);
        }

        return next.handle(req);
    }
}

I have configured this interceptor in my app.module.ts as below

providers: {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpRequestInteceptor,
      multi: true
    }

Here I am trying to pass a custom header value in the get request, but I don't see my header value is passing in the request when I look at the network tab in the chrome.

My Asp.Net Web api code could be.

HttpApplication app = (HttpApplication)sender;
string    user = app.Context.Request.Headers.GetValues("userName").First();

I am getting user name value in the web.api code when I access the url from postman & advanced reset client.

But I am not getting the header value when I access the same api url from Angular 4 application.

Please help me where I am missing.

1 Answer 1

1

Try setHeaders https://angular.io/api/common/http/HttpRequest#clone:

@Injectable()
export class HttpRequestInteceptor implements HttpInterceptor {
    loginUserName = "";
    constructor(private router: ActivatedRoute) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {


        if (environment.Authentication == 1) {           
            // add a custom header


            const newRequest = req.clone({
              setHeaders: { 'userName': '11111' }
            });
            return next.handle(newRequest);
        }

        return next.handle(req);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

The values are getting passed to my service. Do you have any idea how I can get the custom header value(11111) from my request

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.