Angular 5在http get请求中正确传递头文件

时间:2018-05-12 15:06:06

标签: angular angular5

所以最初我使用弃用的HttpModule来处理我的api请求,但我现在正在使用HttpClientModule并且正确地传递头文件有问题。我有一个函数调用api来获取一些数据......这是我最初使用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'));
})

} 所以最初它都与HttpModule一起工作但现在使用HttpClientModule我得到错误

detail:"Authentication credentials were not provided."

如何使用HttpClientModule正确传递标题。

2 个答案:

答案 0 :(得分:0)

最好采用一种处理标题的新方法:使用拦截器

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

答案 1 :(得分:0)

  

详细信息:&#34;未提供身份验证凭据。&#34;

您收到此问题是因为您的标头为空。

使用httpOptions对象发送标头
在新HttpClientModule中,JSON是假设的默认值,不再需要使用res.json()明确解析  建议您使用observables而不是promises。通过转换为承诺,您将失去取消请求的能力以及链接RxJS运营商的能力。

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