vamsi
vamsi

Reputation: 1586

Using Typescript interface as HttpParams in the GET request

I have an interface like below

export interface ValueList {
  attributeId: number;
  attributeName: string;    
}

And my HTTP GET request looks like

public getData(columnId: number, columnName: string) {
  const url = './assets/portfoliolist.json';
  return this.httpClient.get(`${url}?attributeId=${columnId}&attributeName=${columnName}`);
}

So, basically I am not making use of the interface I defined. I am not really sure how can I use that interface in the GET request to build the query parameters? Please suggest. Thanks.

Upvotes: 2

Views: 4271

Answers (2)

Ashish Kumar Jaryal
Ashish Kumar Jaryal

Reputation: 812

If you want to do it inside the getData method then you may do it like this.

public getData(columnId: number, columnName: string) {
    const url = './assets/portfoliolist.json';
    const valueList: ValueList = { attributeId: columnId, attributeName: columnName };

    let httpParams = new HttpParams();
    httpParams = httpParams.append('attributeId', valueList.attributeId.toString());
    httpParams = httpParams.append('attributeName', valueList.attributeName);

    return this.httpClient.get(
      url,
      {
        params: httpParams
      }
    );
  }

You may also extract model and query parameter generation code to any place as required and pass query parameter as input to the getData method.

Upvotes: 1

Rafi Henig
Rafi Henig

Reputation: 6424

Option 1:

getData is declaring a single parameter (of type ValueList) where the values are retrieved using Destrucuring as following:

public getData({ attributeId, attributeName }: ValueList) {
  const url = './assets/portfoliolist.json';
  return this.httpClient.get(`${url}?attributeId=${attributeId}&attributeName=${attributeName}`);
}

Option 2:

public getData(p: ValueList) {
  return this.httpClient.get(`${url}`, { params: new HttpParams({ fromObject: p}) });
}

Upvotes: 3

Related Questions