首页 > 解决方案 > 为什么我会收到“没有重载匹配此调用”错误

问题描述

我需要向某些 API 发出请求。所以为了这个目的,我在我的服务中有这个方法

export interface IFilterAuctionBids {
  filterSupplierName: string;
  filterLocation: string;
  filterBidPrice: number;
  limitResultFlag: boolean;
  filterBidAwardStatus: AuctionBidFilterStatus[]
}

getAuctionBidsByGuidUsingGET(auctionGuid: any, params?: IFilterAuctionBids) {
  console.log('-', params.filterBidAwardStatus);
  return this.http.get(this._GET_AUCTION_URL + '/' + ApiPaths.auction + '/' + auctionGuid + '/bids', {params});
}

从我的组件中,我发送了可选的所需查询参数。

let queryParams = {
  filterBidAwardStatus: ['Awarded']
}
this.getAuctionService
    .getAuctionBidsByGuidUsingGET(this.parametarsURL, queryParams)
    .subscribe((data) => {
...
}

所以我想仅发送 filterBidAwardStatus 查询参数。

但在服务中我得到错误

No overload matches this call.
  The last overload gave the following error.
    Type 'IFilterAuctionBids' is not assignable to type 'HttpParams | { [param: string]: string | string[]; }'.
      Type 'IFilterAuctionBids' is not assignable to type '{ [param: string]: string | string[]; }'.
        Index signature is missing in type 'IFilterAuctionBids'

这是为什么?

我需要具有类型安全性,因此当我发送查询参数时,这些查询参数会遵循我接口的签名。

我试过了

getAuctionBidsByGuidUsingGET(params: GetAuctionBidsByGuidUsingGETParams, queryParams?: IFilterAuctionBids): Observable<__model.AuctionBidPojoListBaseResponse> {
    const httpParams = new HttpParams();
    console.log('queryParams', queryParams);
    Object.entries(queryParams).forEach(([key, value]) => httpParams.set(key,value.toString()));
    return this.http.get(this._GET_AUCTION_URL + '/' + ApiPaths.auction + '/' + params.auctionGuid + '/bids', {params: httpParams});
  }

现在我有类型安全,但值不作为查询参数发送

标签: angulartypescript

解决方案


我认为您收到此错误是因为您试图传递第二种类型的对象

{ [参数:字符串]:字符串 | 细绳[]; }

,它期望您只传递字符串和字符串数组,但您的界面有多种其他类型的数字和布尔属性。您可以创建一个新对象,其中每个属性类型的值都是字符串或字符串数​​组,或者您可以像下面那样做

        getAuctionBidsByGuidUsingGET(auctionGuid: any, params ? : IFilterAuctionBids) {

  const httpParams = new HttpParams(); // create 
    Object.entries(params).forEach(([key, value]) => {

        if (Array.isArray(value)) {
            httpParams.set(key, value.map(val => v.toString())); // convert array: any[] into string[]
        } else {
            httpParams.set(key, value.toString());// insert keys

        }
    }); 

    return this.http.get(this._GET_AUCTION_URL + '/' + ApiPaths.auction + '/' + auctionGuid + '/bids', httpParams);
}

在上面的代码中,我只是遍历您的 IFilterAuctionBids 对象(键和值)并手动将它们分配给 HttpPram 对象。


推荐阅读