Reputation: 3868
I don't know how to call a post service with query string. when we run below url with post method : https://test.data.com/myAPI/Login/authenticateUser?username=temp&password=Temp@123®id=''&versions=1&deviceType=1 in postman its working perfectly fine but don't how to pass query string in ionic 3 code
In below code when we pass query string as param, it gives a bad request error.
return this.http.post("https://test.data.com/myAPI/Login/authenticateUser", params).subscribe((data: any) => {
// let resp = data;
// this.items = JSON.parse(JSON.parse(resp).Data);
console.log('my data: ', data);
}, err => {
console.log(err);
});
Upvotes: 3
Views: 5928
Reputation: 726
Found this in another thread, ES6 and works great with nested objects:
objectToQueryParams(params, keys = [], isArray = false) {
const p = Object.keys(params).map(key => {
let val = params[key]
if ("[object Object]" === Object.prototype.toString.call(val) || Array.isArray(val)) {
if (Array.isArray(params)) {
keys.push("")
} else {
keys.push(key)
}
return this.objectToQueryParams(val, keys, Array.isArray(val))
} else {
let tKey = key
if (keys.length > 0) {
const tKeys = isArray ? keys : [...keys, key]
tKey = tKeys.reduce((str, k) => {
return "" === str ? k : `${str}[${k}]`
}, "")
}
if (isArray) {
return `${ tKey }[]=${ encodeURIComponent(val) }`
} else {
return `${ tKey }=${ encodeURIComponent(val) }`
}
}
}).join('&')
keys.pop()
return p
}
Upvotes: 1
Reputation: 4335
Instead of passing an object you need to pass a string appended to the url like below:
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('username', 'temp');
urlSearchParams.append('password', "Temp@123");
urlSearchParams.append('regid', "");
urlSearchParams.append('versions', "1");
urlSearchParams.append('deviceType', "1");
return this.http.post("https://test.data.com/myAPI/Login/authenticateUser?' + urlSearchParams.toString(), null).subscribe((data: any) => {
// let resp = data;
// this.items = JSON.parse(JSON.parse(resp).Data);
console.log('my data: ', data);
}, err => {
console.log(err);
});
You can check the network tab of your dev console now, the URL in there and postman should be the same.
Upvotes: 5
Reputation: 329
You need to check the params you are posting as post data to the call. Below is the example.
let postData = {};
postData.id = this.id;
postData.name = 'Test';
PostRequest(this.BaseUrl + 'api/admin/edit/question', postData).then(res => {
if (res) {
}
});
double sure the names of params you are sending. Also, need to check if you are sending the proper token value to the request???
Upvotes: 1