首页 > 解决方案 > Angular 没有重载匹配这个调用

问题描述

我正在尝试使用 Angular从flightaware获取数据 Json api。并且所有来自 flightaware 的请求都必须包含用户名和使用基本 HTTP 身份验证标准的 FlightXML 密钥。

代码

  var fxml_url = 'http://flightxml.flightaware.com/json/FlightXML2/';
  var username = 'YOUR_USERNAME';
  var apiKey = 'YOUR_APIKEY';


  this.http.get(fxml_url + 'MetarEx', {
      username: username,
      password: apiKey,
      query: {airport: 'KAUS', howMany: 1}
  }).subscribe(data=>{

    console.log(data)

  })

但我得到的错误是

No overload matches this call.
  The last overload gave the following error.
    Argument of type '{ username: string; password: string; query: { airport: string; howMany: number; }; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }'.
      Object literal may only specify known properties, and 'username' does not exist in type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }'.

有什么想法吗?

标签: angularhttp-headers

解决方案


来自文档:但是,对于某些库,可能需要在 base64 中手动编码“user:key”并将结果作为每个 HTTP 请求的一部分发送到“Authorization”标头中

var fxml_url = 'http://flightxml.flightaware.com/json/FlightXML2/';
var username = 'YOUR_USERNAME';
var apiKey = 'YOUR_APIKEY';
var auth = btoa(`${username}:${apiKey}`);

this.http.get(fxml_url + 'MetarEx', {
  headers: { Authorization: auth },
  params: new HttpParams({fromObject: { airport: 'KAUS', howMany: '1' }})
}).subscribe(data=>{
  console.log(data)
});

推荐阅读