Angular, Http GET with parameter?

AngularTypescript

Angular Problem Overview


I dont know how to make an API call to such a method:

[HttpGet]
[ActionName("GetSupport")]
public HttpResponseMessage GetSupport(int projectid)

Because it is GET but still got a parameter to pass, how to do this? Would it be something like this?

let headers = new Headers();
      headers.append('Content-Type', 'application/json');
      headers.append('projectid', this.id);

      this.http.get('http://localhost:63203/api/CallCenter/GetSupport', { headers: headers })

Angular Solutions


Solution 1 - Angular

Having something like this:

let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('projectid', this.id);
let params = new URLSearchParams();
params.append("someParamKey", this.someParamValue)

this.http.get('http://localhost:63203/api/CallCenter/GetSupport', { headers: headers, search: params })

Of course, appending every param you need to params. It gives you a lot more flexibility than just using a URL string to pass params to the request.

EDIT(28.09.2017): As Al-Mothafar stated in a comment, search is deprecated as of Angular 4, so you should use params

EDIT(02.11.2017): If you are using the new HttpClient there are now HttpParams, which look and are used like this:

let params = new HttpParams().set("paramName",paramValue).set("paramName2", paramValue2); //Create new HttpParams

And then add the params to the request in, basically, the same way:

this.http.get(url, {headers: headers, params: params}); 
//No need to use .map(res => res.json()) anymore

More in the docs for HttpParams and HttpClient

Solution 2 - Angular

For Angular 9+ You can add headers and params directly without the key-value notion:

const headers = new HttpHeaders().append('header', 'value');
const params = new HttpParams().append('param', 'value');
this.http.get('url', {headers, params}); 

Solution 3 - Angular

Above solutions not helped me, but I resolve same issue by next way

private setHeaders(params) {      
        const accessToken = this.localStorageService.get('token');
        const reqData = {
            headers: {
                Authorization: `Bearer ${accessToken}`
            },
        };
        if(params) {
            let reqParams = {};        
            Object.keys(params).map(k =>{
                reqParams[k] = params[k];
            });
            reqData['params'] = reqParams;
        }
        return reqData;
    }

and send request

this.http.get(this.getUrl(url), this.setHeaders(params))

Its work with NestJS backend, with other I don't know.

Solution 4 - Angular

Just offering up a helpful piece of code for anyone interested in the HttpParams direction mentioned in the answer from 2017.

Here is my go-to api.service which kind of "automates" params into that HttpParams for requests.

import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Params } from '@angular/router';
import { Observable } from 'rxjs';
import { environment } from '@env';

@Injectable({
    providedIn: 'root'
})
export class ApiService {

    constructor(private http: HttpClient) { }

    public get<T>(path: string, routerParams?: Params): Observable<T> {
        let queryParams: Params = {};
        if (routerParams) {
            queryParams = this.setParameter(routerParams);
        }
        console.log(queryParams);
        return this.http.get<T>(this.path(path), { params: queryParams });
    }

    public put<T>(path: string, body: Record<string, any> = {}): Observable<any> {
        return this.http.put(this.path(path), body);
    }

    public post<T>(path: string, body: Record<string, any> = {}): Observable<any> {
        return this.http.post(this.path(path), body);
    }

    public delete<T>(path: string): Observable<any> {
        return this.http.delete(this.path(path));
    }

    private setParameter(routerParams: Params): HttpParams {
        let queryParams = new HttpParams();
        for (const key in routerParams) {
            if (routerParams.hasOwnProperty(key)) {
                queryParams = queryParams.set(key, routerParams[key]);
            }
        }
        return queryParams;
    }

    private path(path: string): string {
        return `${environment.api_url}${path}`;
    }
}

Solution 5 - Angular

An easy and usable way to solve this problem

getGetSuppor(filter): Observale<any[]> {
   return this.https.get<any[]>('/api/callCenter/getSupport' + '?' + this.toQueryString(filter));
}

private toQueryString(query): string {
   var parts = [];
   for (var property in query) {
     var value = query[propery];
     if (value != null && value != undefined)
        parts.push(encodeURIComponent(propery) + '=' + encodeURIComponent(value))
   }
   
   return parts.join('&');
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser8090896View Question on Stackoverflow
Solution 1 - AngularDGarvanskiView Answer on Stackoverflow
Solution 2 - AngularYassir KhaldiView Answer on Stackoverflow
Solution 3 - AngularV.TurView Answer on Stackoverflow
Solution 4 - AngularBen RacicotView Answer on Stackoverflow
Solution 5 - AngularMalik HaseebView Answer on Stackoverflow