CE0
CE0

Reputation: 191

Angular 5 pass headers properly in http get requests

so initially i was using the deprecated HttpModule for my api requests but i'm using the HttpClientModule now and having issues with passing headers correctly. i've got a function that calls api to get some data...this is what i had initially with HttpModule

service.ts

export class userService {
  //using HttpModule
  getCurrentProfile() {
    let v = this.page_header();
    return this.http.get(this.userProfileUrl, {headers: headers})
      .toPromise()
      .then(response => response.json())
      .catch(this.handleError);
  };

  //using HttpClientModule
  getCurrentProfile() {
    let headers = new HttpHeaders();
    return this.http.get(this.userProfileUrl, {headers: headers})
      .toPromise()
      .then(response => response.json())
      .catch(this.handleError);
  };

  private page_header() {
    let data = localStorage.getItem('auth_token');
    let headers = new Headers();
    let opt: RequestOptions;
    headers.append('Authorization', 'JWT ' + data);
    opt = new RequestOptions({ headers: headers });
    return opt;
  }
}

component.ts

getStoreProfile() {
 //using HttpModule
 this.userSrv.getCurrentProfile().then(response => {
   localStorage.setItem('store', JSON.stringify(response));
   this.profile = JSON.parse(localStorage.getItem('store'));
 }).catch(err => this.error = err)

 //using HttpClientModule
 this.userSrv.getCurrentProfile().subscribe(res => {
  let data = res;
  localStorage.setItem('store', JSON.stringify(res));
  this.profile = JSON.parse(localStorage.getItem('store'));
})

} So initailly it all worked with HttpModule but now with HttpClientModule i get errro

detail:"Authentication credentials were not provided."

How am i to pass headers correctly using HttpClientModule.

Upvotes: 0

Views: 2731

Answers (2)

Vikas
Vikas

Reputation: 12036

detail:"Authentication credentials were not provided."

You are getting this issue because your header is empty.

use httpOptions object to send header
In new HttpClientModule JSON is an assumed default and no longer needs to be explicitly parsed using res.json()
it's recommended to use observables over promises. By converting to a promise you will lose the ability to cancel a request and the ability to chain RxJS operators.

 getCurrentProfile():Observable<any> {
    let data = localStorage.getItem('auth_token');
      const httpOptions = {
                headers: new HttpHeaders({
                    'Content-Type':  'application/json',
                        'Authorization': ' 'JWT ' + data'
         })
    };

        return this.http.get(this.userProfileUrl, httpOptions)
         .catch(this.handleError);
      };

Upvotes: 0

Rohit.007
Rohit.007

Reputation: 3502

Better you adopt a new way of handling the Headers: Use the Interceptor

import { AuthService } from './auth/auth.service';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(public auth: AuthService) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${this.auth.getToken()}`
      }
    });
    return next.handle(request);
  }
}

Upvotes: 1

Related Questions