I am testing ionic4 app. one http post value response is like below
var link = ‘http://localhost/testapi/index.php/Login/login’;
var myData = JSON.stringify({username: this.loginForm.value.username,password:this.loginForm.value.password});
this.http.post(link, myData)
.subscribe(data => {
this.data.response = data["_body"];
console.log(this.data.response); // result is like ==>
{“results”:[{“status”:true,“username”:“as”,“id”:“8”,“token”:“eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjgifQ.lkSaJwbxihvVX66gpWNX615uSpAmLonf0r-g2pou5GE”}]}
I need to separate each key and its value in this ts file.
like status=true,username=as etc
I got this solution for my problem
var test= JSON.parse(this.data.response) ;
var key;
for (var event in test) {
var dataCopy = test[event];
for (test in dataCopy) {
var mainData = dataCopy[test];
for (key in mainData) {
console.log( key + ' : ' + mainData[key]);
}
}
}
reference https://stackoverflow.com/questions/14028259/json-response-parsing-in-javascript-to-get-key-value-pair
By convention, leading underscores mean “hands off”. If you’re using HttpClient
, all you have to do is properly type your post
call. This can all be simplified into a one-line function:
interface LoginRequest {
username: string;
password: string;
}
interface LoginResponse {
status: boolean;
token?: string;
// other stuff here
}
login(req: LoginRequest): Observable<LoginResponse> {
return this.http.post<LoginResponse>(link, req);
}