Angular HttpClient Get method with body

前端 未结 4 1483
一整个雨季
一整个雨季 2020-12-15 16:57

I\'m improving an existing API, and the requirement is to provide a single get method which can accept multiple search criteria and based on those criteria perform the query

4条回答
  •  甜味超标
    2020-12-15 17:26

    To make Amir's answer some more generic I have done the following to build params for the passed item.

    To my generic data service I have added this variant:

    // Get data for passed parameters or item containing filters
    public getByItem(apiMethod: string, item?: T, apiParms?: HttpParams): Observable {
        if (!apiParms) apiParms = new HttpParams();
        if (item) {
            const keys = Object.keys(item) as Array;
            for (let key of keys) {
                apiParms = apiParms.append(key.toString(), item[key].toString());
            }
        }
        // Call generic method of data service
        return this.get(apiMethod, apiParms); // => return this.http.get(environment.apiUrl + apiMethod, { headers: this.defaultHeaders
    

提交回复
热议问题