首页 > 解决方案 > 无法在 httpclient 中设置自定义标头(ionic 3 app angular 5)

问题描述

我正在尝试使用需要 API 密钥“Auth”的 api,我正在尝试使用以下代码使用 httpHeaders 发送密钥

getTest(){
let data = {'loginusertype':'12','loginuserid':'51','apitype':'1','start':'0','end':'20'};
let headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8','Auth':'593eb2c274d640a8798493bf340e08b6'});
this.http.post('http://www.mymediaxchange.com/api/serviceapi/v1/currentworks',data,{headers:headers})
.subscribe(
  (data) => console.log(data),
  (error) => console.log(error)
)  }

但我无法设置标题标题设置如下在此处输入图像描述

我尝试过的事情
1)使用的拦截器
2)这个问题中的解决方案
Angular HttpClient 不发送标头
3)this.http.post('mymediaxchange.com/api/serviceapi/v1/currentworks',data,{headers: {'Auth': 'YourAuthorizationKey'}})

标签: angularapiionic-frameworkionic3angular5

解决方案


您可以尝试为此使用拦截器服务。它的作用是为应用程序的每个请求添加一个 Authorization 标头。

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // add authorization header with token
    const currentUser = JSON.parse(String(localStorage.getItem('currentUser')));
    if (currentUser && currentUser.Token) {
      request = request.clone({
        setHeaders: {
          Authorization: `${currentUser.Token}`
        }
      });
    }
    return next.handle(request);
  }
}

并在您的模块提供程序部分使用它。

providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useClass: JwtInterceptor,
          multi: true
        }
      ]

推荐阅读