1

I want to add headers to post request from Angular 5 web app. I've created the following Injectable class, registered in my app module:

@Injectable()
    export class headerInterceptor implements HttpInterceptor {
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {    
        // Clone the request to add the new header         
        const authReq = req.clone({
          headers: new HttpHeaders({
            'Content-Type':  'application/json; charset=utf-8',        
          })
        });        
        return next.handle(authReq);


      }
    }

I have network communication service and Im adding body parameters as below.

@Injectable()
export class NetworkService {

  Root:string = 'some valid url';
  results:Object[];
  loading:boolean;

  // inject Http client to our client service.
  constructor(private httpClient: HttpClient ) {

  }



  login(loginParams : URLSearchParams){    
    let baseURL = `${this.Root}/login`;                    
    this.httpClient.post(baseURL, JSON.stringify({'UserName':'123','Password':'123'} ))
    .subscribe(data => {
        console.log();
    },
    err => {
          console.log('Error: ' + err.error);
      });

when I put breakpoint after the clone method inside headerInterceptor class I can see the request body. the problem is when I switch to network tab in chrome, I get 405 error and I can't see the body and the new headers. when I return the original request 'req' the body sent ok but no new headers of course.

4
  • have you added that interceptor to providers array in app module? Commented Mar 27, 2018 at 12:31
  • yes: { provide: HTTP_INTERCEPTORS, useClass: headerInterceptor, multi: true } Commented Mar 27, 2018 at 12:32
  • why the const? Commented Mar 27, 2018 at 12:42
  • no must, but its not the problem Commented Mar 27, 2018 at 12:52

2 Answers 2

5

App Module,

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { headerInterceptor } from './httpinterceptor'

Add it to providers,

providers: [
{
    provide: HTTP_INTERCEPTORS,
    useClass: headerInterceptor,
    multi: true
}
],

Now change the intereptor to, I have changed the way headers are added

@Injectable()
    export class headerInterceptor implements HttpInterceptor {
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const authReq = req.clone({
              headers:req.headers.set("Content-Type", "application/json; charset=utf-8")
        });
        return next.handle(authReq);
      }
    }
}

You can also use setHeaders:

@Injectable()
export class headerInterceptor implements HttpInterceptor {
  constructor() {}
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {y
    req = req.clone({
      setHeaders: {
        "Content-Type": "application/json; charset=utf-8"
      }
    });
    return next.handle(req);
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

@Savaran, your answer is correct but my problem was sever side.
yeah its fine, the final outcome should be you should get an answer and I m happy that its solved for you. :-)
0

My problem was on server side I'm using ASP.net and wcf. it seems that the server must implement CORS support when working with Angular 5 project (works ok with jQuery and cross domain tag).

this post helped me to add support in CORS:

http://blogs.microsoft.co.il/idof/2011/07/02/cross-origin-resource-sharing-cors-and-wcf/

Comments

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.