Karthikeyan
Karthikeyan

Reputation: 319

Angular 4 with custom request header

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.

Upvotes: 0

Views: 960

Answers (1)

vegazz
vegazz

Reputation: 1441

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);
    }
}

Upvotes: 1

Related Questions