As a novice in Ionic and TypeScript, I am facing an issue with accessing an API. The API can only be accessed using the POST method with parameters passed in the body for security reasons. I need to retrieve JSON data from this API but I'm unsure how to pass the parameters in the body.
Below is the code snippet that I have attempted:
sample.ts
import { Component } from '@angular/core';
import { IonicPage, NavParams } from 'ionic-angular';
import {HttpProvider} from '../../providers/http/http';
import { NavController, LoadingController } from 'ionic-angular';
import { TraineristorePage } from '../traineristore/traineristore';
import { StorePage } from '../store/store';
import 'rxjs/add/operator/map';
import {Http,HttpHeaders} from '@angular/http';
import {RequestOptions, Request, RequestMethod} from '@angular/http';
@IonicPage()
@Component({
selector: 'page-sample',
templateUrl: 'sample.html',
providers:[HttpProvider]
})
export class SamplePage {
users: any;
headers:Headers;
options:RequestOptions;
constructor(public navCtrl: NavController, private loadingCtrl:
LoadingController, public navParams: NavParams, private
httpProvider:HttpProvider, public http:Http) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad SamplePage');
}
loadJson(){
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
let options = new RequestOptions({ headers: headers });
let data="token="+""+
"&searchvalue="+""+
"&sortby="+""+
"&sorttype="+""+
"&filter="+""+
"&startfrom="+""+
"&limit="+""+
"&producttype=1";
this.http.post('this is my API URL', data, options)
.map(res => res.json())
.subscribe(res => {
this.users = res.data;
console.log(this.users);
},
(err) => {
alert("failed to load json data");
});
}
}
Below is the corresponding HTML file sample.html:
<button ion-button (click)="loadJson()">Load Data</button>
<ion-list>
<ion-item class="col" *ngFor="let user of users" >
<p class="t"> {{user.productid}}</p>
<ion-icon class="icon" name="ios-heart-outline" md="md-heart"></ion-icon>
<br>
<p class="p">ProductId : {{user.name}}</p>
<!--<img class="img" src="{{user.productImg}}" width="97px" height="86px" ng-click="nextpage()">
<p class="p">Rs {{user.price}}</p>
--><hr>
</ion-item>
</ion-list>
I would greatly appreciate any suggestions or insights you may have. Thank you in advance.