Hi I am trying to get data using http get request and query string.
I want the get http url to be 'baseUrl' + 'querystring' like http://randomUrl.com/?var1=val1&var2=val2
I tried using URLSearchParams like below but somehow, instead of getting 'var1=val1&var2=val2' as querystring, I am getting http://randomUrl.com/?[object%20Object]
Below is my code. What am I doing wrong?
In the global HttpClientService,
get(path: string): Observable<any> {
const headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Access-Control-Allow-Headers', 'Content-Type');
headers.append('Access-Control-Allow-Methods', 'GET');
headers.append('Access-Control-Allow-Origin', '*');
headers.append("X-Requested-With", "XMLHttpRequest");
let options = new RequestOptions({ headers: headers });
return this.http.get(`${baseURL.baseurl}${path}`, options)
.map(this.extractdata)
.catch(this.handleError);
}
In the Service, @Injectable() export class GetDataService {
constructor(private http: HttpClient) { }
getData(queryparams): Observable<any> {
return this.http.get('/front/search?' + `${queryparams}`)
}
}
In the component using above service,
getData(): void {
let params = new URLSearchParams();
params.set('var1', 'val1')
params.set('var2', 'val2')
params.set('var3', 'val3')
this.getdata.getData({search:params})
.subscribe
(
data => this.data = data,
error => this.errorMessage = error
)
}
ngOnInit(): void {
this.getData();
}
I appreciate your help in advance
${queryparams.rawParams}give you the string back? - DeborahK