A guide to sending parameters in the URL body using TypeScript for a REST API on the Ionic framework

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.

Answer №1

Instead of using JavaScript, you can directly call the API in Ionic framework.

var apiLink = "Your API Endpoint";
  var requestBody = JSON.stringify({mno: mobileNumber, pwd: password});

  return new Promise(resolve=>{
        this.http
        .post(apiLink, requestBody)
        .map(res=>res.json())
        .subscribe((data : any) =>
        {

          this.responseData = data;
          console.log(this.responseData);

        },
        (error : any) =>
        {
           console.dir(error);
        });
        });

Answer №2

To achieve the body parameter in a URL, I've implemented JavaScript in Ionic.

 function fetchData(){
 $.post("http:xxxxxxxxxx/"+"listProducts",
      {  
 "token" : ''  ,
 "searchvalue" : '' , //Product Name
 "sortby" : '' , //Brand
  "sorttype" : '' , //asc,desc
  "filter" : '' , //Category
  "startfrom" : '' , //1,2, etc
  "limit" : '',  //1,10,4,5, etc
   "producttype" : '1'  //1 Suppliments or 2 accessories
     }, 
      function(data,status){
      var d = JSON.parse(data);
     }
 }

This code successfully retrieves JSON data from the API. Hopefully, it will be useful to someone else. Thank you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The recursive component is functional exclusively outside of its own scope

I'm facing an issue where my recursive component is not nesting itself properly. The problem arises when I try to use the Recursive component inside another Recursive component. Although the root is correctly inserted into the Recursive component fro ...

Transferring information through parent-child components via onChange

I have a question regarding data binding. In my project, I have a parent component and two child components: Parent: directives: [firstChild,secondChild], template:' <first-child [showList]="showList" (emitShowList)="getShowList($event)"& ...

A layout featuring nested buttons and links within a card element, utilizing the power of Link in NextJs

After extensive searching on S.O., I have been unable to find a solution that works flawlessly. The issue at hand involves a card component in a NextJs application that is encompassed within a <Link> tag. Additionally, there is another <Link> t ...

Tips for simulating a callback function to evaluate a promise using jasmine in an Angular 8 environment

I'm struggling with figuring out how to mock a callback function and the function that calls it. The specific function I'm trying to mock is "listenOnAMessageWithCallBack" from a service I'm injecting, along with the callback function it tri ...

Tips for preventing the need to cast a DOM element to any in Typescript

In my Typescript code, I am retrieving the value of a DOM element like this: document.getElementById('MyElementId') as HTMLElement).value I feel unsure about casting it to HTMLElement. Is there a better way to specify the type and retrieve this ...

Encountering TypeScript error TS2345 while attempting to reject a Promise with an error

I recently encountered a perplexing TypeScript error message that I am struggling to comprehend. The specific error reads as follows: error TS2345: Argument of type '(error: Error) => void | Promise' is not assignable to parameter of type & ...

Is it possible for Typescript to allow extracted interfaces while excluding properties from another interface?

I've been searching for information on the specific features of this. Despite my efforts on Google, I have been unable to find the details. Any help would be greatly appreciated! interface Numbers { number: number; number2: number; number ...

Issue with typescript 1.8 Angular2 rc1 when trying to inject a JavaScript library (auth0.js): Module 'auth0' not found

I am facing an issue while trying to integrate the auth0.js library into my Angular2 rc1 TypeScript project for a custom signup feature. When I try to inject the auth0 library into my components, TypeScript throws a "Cannot find module 'auth0'" e ...

The application denied the request to establish an insecure header with the label "Host", communicating using Ionic framework

Despite setting the access-control-allow-origin →* header in the response header from the server side, I am still unable to access the data from the Chrome browser. My approach in Ionic for loading data is as follows: var h = new Headers(); h.set("Host ...

analyzing properties through unit testing

Currently in the process of writing unit tests for computed properties. I have a file called fileOne.ts : export const fileOne = () => { const fx1 = computed ( () => { ... } ); const fx2 = computed ( () => { ... } ); const fx3 = comp ...

Encountering an issue while attempting to import the react-autosuggest module, receiving the following error

I recently encountered an issue while trying to import the react-autosuggestion module in my TypeScript file on Ubuntu v18 OS. Initially, I executed the following command: sudo npm install react-autosuggest --save import Autosuggest from 'react- ...

Muting the unused variable alert in JavaScript

Whenever I run my typescript compiler, it always gives me errors about unused variables. In C programming, I would prevent this using the following method: void foo(int bar) { (void)bar; } Is there a similar workaround in JavaScript? ...

Having trouble accessing the database in Angular and Ionic through a provider on a Tabbed page

I created a Home page with tabs using Ionic 3 and Angular. The tabs are named Stats and Calc. When clicking on the Stats tab, it triggers the class/component stats.ts (displayed below). This component utilizes two providers: CropProvider and ContractProvi ...

Error encountered: NextJs could not find the specified module, which includes Typescript and SCSS

I am in the process of migrating a Next.js application from .js to .ts and incorporating ScSS. The first error I encounter is during 'npm run dev'. However, when I try 'npm run build', different issues arise that do not seem related to ...

What causes the dispatch property to be undefined in a connected wrapped component within a connected Higher Order Component while using react-redux in conjunction with typescript?

As a new user, I am facing a particular challenge. I am working with a Higher Order Component (HoC) that injects properties into a wrapped component. The HoC itself returns a React.ComponentClass that is connected to the redux store with mapped and dispatc ...

I continuously encounter an issue in Vite version 3.2.4 where an error pops up stating `[vite:esbuild] The service has stopped running: write EPIPE`

When I finished creating a Vite app, I ran the command npm run dev and encountered the following error: [vite:esbuild] The service is no longer running: write EPIPE https://i.stack.imgur.com/MZuyK.png I need help solving this error. Can anyone provide gu ...

Transform current JSON data into formatted JSON format using JavaScript or TypeScript

I have a JSON structure that needs to be reformatted in order to meet the requirements of an external service. Although the current format is complex and cannot be altered, I need to modify it to match the desired output for the external service. Current ...

The issue of excessive recursion in Typescript

Currently, I am in the process of learning Typescript while working on some exercises. While attempting to solve a particular problem, I encountered an error related to excessive recursion. This issue arises even though I created wrapper functions. About ...

When running tests with "Playwright Test for VS Code", the Console.log function fails to display any logs

While running my Playwright tests in TypeScript, I've noticed that the logs are not showing up on the console. Even though I have console.log statements in my code that appear fine when debugging the tests in the "Debug Console" tab, they do not disp ...

How to reference an array from one component to another in Angular 2

Within my AddUserComponent, I have a public array declared like this: public arr: Array<any> = [] This array stores the names of users. Now, I need to access these values in another component called AddTopicComponent in order to display the user&a ...