0

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.

2 Answers 2

1

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);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

4 Comments

using your code i encountered some error on ide so i tried fixing but one more red line property 'json' does not exist on type 'object' here is what i have getCurrentProfile() { 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) .toPromise() .then(response => response.json()) .catch(this.handleError); }; red line just after .toPromise()...sorry code not format properly
Oh la la...thanks man, working now. issue was really in the header, had to console.log and see then concatenate properly...now it is working. Thanks really.
Glad I could help :)
It helped me to set the headers for api call. But, i have one question in my api call header. i'll be having more than one header property like Access-Token, User-ID and User-IP how to set these property accordingly? @Vikas

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.