Search code examples
angularangular5angular-httpclient

passing optional query string parameters to http service call


i need to make an API call which allows me to pass through optional query sting params

 retrieveConts(param1:string,param2?:string):Observable<IContracts> {  
  this.basePath =  "/myConts"; 
      return http.get(this.basePath,{ 
      params: {  
       arg1:param1,
       arg2:param2,
      },
      withCredentials: false
    }) 
     .catch(this._errorHandler); 
  }

With the above code spinet, i have declared param2 as an optional parameter which can or cannot be passed through to the service call, however if param2 gets no value, it then returns undefined for which its understandable.

How do i make the service call to ignore the "arg2" parameter if no value was returned from the param2 variable?


Solution

  • You can do something like this:

    retrieveConts(param1:string,param2?:string):Observable<IContracts> {  
        this.basePath =  "/myConts"; 
        let params = {arg1: param1};
        if (param2)
            params = {arg1: param1, arg2: param2};
    
        return http.get(this.basePath, { 
            params: params,
            withCredentials: false
        }) 
        .catch(this._errorHandler); 
    }
    

    Hope this will be helpful!