Angular 5 pass headers properly in http get requests

送分小仙女□ 提交于 2019-12-11 14:51:42

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/50307636/angular-5-pass-headers-properly-in-http-get-requests

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!