0

I have these methods in my auth.service and an auth.interceptor.ts code in order to take the token from header and I want to send it with post method what should add in header in order to set the token? Any help is much appreciated!!

 //shop.service.ts

const httpOptions = {

headers: new HttpHeaders({ 'Content-Type': 'application/json', 
'Authorization': 'X-OBSERVATORY-AUTH'}) 

};

addShop (shop: Shop): Observable<Shop> {

return this.http.post<Shop>(this.shopsUrl, shop, httpOptions);
}


// auth.interceptor.ts

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

  const authToken = this.authService.getToken();

  const authRequest = req.clone({

    headers: req.headers.set("Authorization", "Bearer " + authToken)

  });

  return next.handle(authRequest);
}



//auth.service.ts

getToken() {
return this.token;
}


login( username: string,  password: string) {

var user: User = {  username: username, password: password };
this.http 
  .post<any>("http://localhost:3000/observatory/api/login",user, 
   {observe:'response'})
  .subscribe((res) => {
    const token = res.headers.get('X-OBSERVATORY-AUTH');
    console.log(token);
    this.token = token;

    if (token!==null) {

      this.isAuthenticated = true;
      this.userId = res.body._id;
      this.isAdmin=res.body.isAdmin;
      this.userAdmin=res.body.isAdmin;
      this.username=res.body.username;
      this.authStatusListener.next(true);
      this.saveAuthData(token, this.userId,this.username, this.isAdmin);

} });

Christy Nakou
  • 393
  • 1
  • 2
  • 14
  • You can make use of interceptor, someone already wrote an article for that [Medium link](https://medium.com/@ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8) – Chenna Mar 02 '19 at 18:00
  • I have this interceptor..how can I use it? wait please to add the code I have in the question form – Christy Nakou Mar 02 '19 at 18:06

2 Answers2

0

You're nearly there. shop.service.ts should add headers just fine. Do the same in auth.service.ts:

this.http.post<any>(url, user, { 
    headers: new HttpHeaders({ 
      'Content-Type': 'application/json', 
      'Authorization': 'X-OBSERVATORY-AUTH'
    }), 
    observe: 'response'
  });

Docs: https://angular.io/guide/http#adding-headers

To add headers on ALL (or almost all) HTTP requests, use a HTTP Interceptor (see @Chenna 's comment)

Edit:

Apologies for posting untested code. See Angular 4/5 HttpClient: Argument of type string is not assignable to 'body' for why the previous version produced an error. In short, you need to either inline the observe or use a few ugly tricks.

OR: use a HTTP Interceptor. End of all your worries.

Jasmonate
  • 752
  • 1
  • 8
  • 18
  • I copied it in my code and the console returned an error: – Christy Nakou Mar 02 '19 at 18:22
  • Error:Argument of type '{ headers: HttpHeaders; observe: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }'. Types of property 'observe' are incompatible. Type 'string' is not assignable to type '"body"'. – Christy Nakou Mar 02 '19 at 18:23
0

You already have the interceptor created. You just need to provide it in the module so it can intercept the requests.

providers: [{ provide: HTTP_INTERCEPTORS, useClass: YourInterceptorClass, multi: true }]
Sachin Gupta
  • 4,981
  • 3
  • 16
  • 32