The number entered will be incorporated into the API URL key value by passing the variable from page.html to services.ts

Recently diving into the world of Ionic, Angular, and Typescript, I've had a burning question. Can the number inputted be added to the API URL as one of the key values? I came across this helpful guide, specifically focusing on key event filtering (with key.enter).

Let's take a look at my page.html setup:


    <ion-input placeholder="Number" [(ngModel)]="myNum"  (keyup.enter)="onEnter()"></ion-input>

  <ng-container *ngIf="!error; else errorContent">
  
    <p *ngFor="let order of orders; let i=index;">
      <ion-item *ngIf="i==0">Number : <b>{{ order?.Number }}</b></ion-item>

      <ion-item class="listDetails">
      
        <p class="listTitle">
          {{order?.status }}
          <br />
          <a>
            {{ order?.date | date: 'MMM dd, yyyy' }}
            <br />
            {{ order?.time }}
          </a>
        </p>

        <p class="listComment">
          {{ order?.comment }}
        </p>

      </ion-item>

Furthermore, here is an example of how my API URL would look like with the dynamic insertion of the inputted number:

''+myNum

Delving deeper, let me share some snippets from my page.ts file:


constructor(private dataService: DataService, private http: HttpClient) {
  this.data = '';
  this.error = '';
}


orders= [];
ionViewWillEnter() {
  // Load the data
  this.dataService.getRemoteData(this.myNum).subscribe( 
    data => {
      this.orders = data.output.Result.FoodOrderTracking;
    },
    err => {
      this.error = `An error occurred, the data could not be retrieved: Status: ${err.status}, Message: ${err.statusText}`;
    }
  );
}

this.dataService.getRemoteData(this.myNum).subscribe(data => {
  console.log("Remote Data:");
  console.log(data);
});

onEnter () {

  this.dataService.getRemoteData(this.myNum).subscribe(data=>
  {
    console.log('data', data)
  })
}   

Next up, let's explore my data.services.ts responsible for fetching data from the API url:


import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  myNum = ''
  onEnter (docNum: string) {this.myNum = myNum}
  apiUrl = 'http://127.0.0.1:8080/https://myapi.com/FoodDeliveryTracking?&userName=myuser&password=mypass&MyNumber='+myNum';
  apiKey = ''; 

  constructor(private http: HttpClient){}

  getRemoteData(){
    let headers = new HttpHeaders({'apiKey': this.apiKey});
    headers.append('Accept','application/json');
    headers.append('X-Requested-With','XMLHttpRequest');
    headers.append('content-type','application/json');
    return this.http.get(this.apiUrl, {headers: headers});
  }

}

Lastly, you might be wondering how to pass a variable from the input in page.html to services.ts. Is it achievable? Check out this snippet:

myNum = Data entered from the ion-input on my html.page

Answer №1

Give this a try

Implement databinding in your HTML template

 <ion-input placeholder="Enter Number" [(ngModel)]="myNum" (keyup.enter)="onEnter()"></ion-input>

component.ts

Update the onEnter function in your component to make a call to the service

onEnter () {

  this.dataService.getRemoteData(this.myNum).subscribe(data=>
  {
    console.log('data', data)
  })
}   

dataservice.ts

Use the base URL for the API endpoint

 apiUrl = 'http://127.0.0.1:8080/https://myapi.com/FoodDeliveryTracking';

Modify the getRemoteData method to utilize HttpParams for sending query parameters.

getRemoteData(myNum: string){
    let headers = new HttpHeaders({'apiKey': this.apiKey});

    //Set query string parameters
    let params = new HttpParams()
    .set('MyNumber', myNum) 
    .set('userName','myuser')
    .set('password','mypass');

    return this.http.get(this.apiUrl, {headers, params}).subscribe(data =>console.log('data', data));
}

Take a look at this example code on StackBlitz. Please note that the HTTP request may not succeed as the API URL is non-existent, but you can observe all parameters being sent in the network debugger

Answer №2

From my understanding, the variable myNum is being updated while apiUrl remains unchanged.

To resolve this issue, you can convert apiUrl into a computed property like below:

get apiUrl () {
  return 'http://127.0.0.1:8080/https://myapi.com/FoodDeliveryTracking?&userName=myuser&password=mypass&MyNumber=' + this.myNum';
}

This adjustment ensures that the URL is dynamically generated based on changes to the myNum value rather than just once during the service initialization.

Additionally, it's essential to properly encode this parameter for URL usage. If it's a number, consider enforcing it by including type="number" within your <ion-input>. Alternatively, utilize encodeURIComponent before appending it to the URL.

Answer №3

const params = {'name': 'John', 'age': 30};

const urlString = new URLSearchParams(myParams).toString();

console.log(urlString);

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

Get the Highchart image downloaded within your Phonegap mobile application

Our team is currently working on a mobile app with the combination of Phonegap + Ionic. We have integrated Highcharts into our app and now we are looking to add a feature that allows users to share the Highchart on platforms like Facebook, Whatsapp, and Tw ...

Converting a text[] array to a json[] array in Postgres

I am facing a challenge with a generated SQL statement that is outputting arrays like array['{"foo": "bar"}'] The problem lies in the fact that these arrays are of type text[]. What I really need is an array of type json[], w ...

What steps should I take to ensure the successful function of the App Routing system in this scenario?

After creating an Angular App, I encountered a challenge in one of my services. When I call the http.post method and subscribe to it, I aim to redirect to the previous page with a parameter (e.g., "http://localhost:3000/profile/aRandomName"). Unfortunately ...

Retrieve numerous tables as individual entities in a single query

In the process of creating an interface where the selection in the first dropdown influences the available options in six subsequent dropdowns. For each dropdown, the values and display names are retrieved from a table as shown below: $arr = arra ...

Discovering the category for ethereum, provider, and contract

My current interface looks like this: interface IWeb3 { ethereum?: MetaMaskInpageProvider; provider?: any; contract?: any; }; I was able to locate the type for ethereum using import { MetaMaskInpageProvider } from "@metamask/providers", ...

There are no call signatures available for the unspecified type when attempting to extract callable keys from a union

When attempting to write a legacy function within our codebase that invokes methods on certain objects while also handling errors, I encountered difficulty involving the accuracy of the return type. The existing solution outlined below is effective at cons ...

Create a new JSON file and add data using ObjectMapper

My current project involves delving into Jackson to gain a better understanding of how it works. I am in the process of creating a simple program that can both read from and write to a file, specifically storing JSON data in it. This project revolves aroun ...

Having trouble utilizing the DatePicker component in my react native application

I've encountered an issue while using DatePicker in react native. Whenever I try to use it, an error pops up saying: "render error a date or time must be specified as value prop". Here is the link to my repository: my github repository const [date, se ...

Arrange two input fields side by side if the quantity of input fields is unspecified

I am currently in the process of developing a project using Angular. I have implemented an *ngFor loop to dynamically add input fields based on the data retrieved from the backend. Is there a way I can ensure that two input fields are displayed on the same ...

What is the correct method to remove an item from local storage?

Using localStorage, I have stored multiple objects in an array. Is there a way to remove just one object from this array? If I use localstorage.removeItem(keysofthelocalstorage), I can delete the entire array, but I specifically want to remove only certai ...

Gson in action - managing and accessing an ArrayList containing complex objects

I have a class named NameAndPosition that stores the name and position of users. I've created an ArrayList to hold objects of type NameAndPosition. ArrayList<NameAndPosition> LocSenders = new ArrayList<NameAndPosition>(); Using the Gson ...

Utilizing Functions in Next.js with TypeScript: A Guide to Reusability

It is considered a best practice to separate data fetching functions into a folder named services, but I'm having trouble implementing this in my Next.js project. The function works when placed inside the component where I want to render the data, but ...

You must pass a string, Buffer, ArrayBuffer, or Array as the first argument when using Uint8Array.slice(). A number was received instead

Here is my implementation of the ByteArray class, which extends the Uint8Array class. export class ByteArray extends Uint8Array { ... private _encoded: string; ... constructor(_encoded: string) { super(Buffer.from(_encoded, " ...

Utilize decorators for enhancing interface properties with metadata information

Can decorators be utilized to add custom information to specific properties within an interface? An example can help clarify this: Interface for App state: export interface AppState { @persist userData: UserData, @persist selectedCompany: UserCo ...

The ExpressJS Req.method TypeError occurs when attempting to read the 'method' property of an undefined object

My node express server is throwing an error: Error in index.js. const bodyParser = require('body-parser'), express = require('express'), path = require('path'); const config = require('./config'); con ...

transform JSON structure into an array

Is it possible to convert an interface class and JSON file into a list or array in order to work on it? For example, extracting the Racename from each object in the JSON file and storing it in a list/array. Here is the interface structure: interface IRunn ...

TypeScript typings for generic currying functions

I'm struggling to improve my skills in functional programming, particularly when dealing with typing generic "curry" functions. One example is a "Curry" version of the reduce function that I've written: const reduce = <S, R>(fn: (result: R ...

Is the code executed within a specific zone, and if it is, what are the reasons and methods for

Recently, I came across the code for the angular material google map library, and most of it made sense to me. However, there is one section in particular that still puzzles me (found in map-event-manager.ts). /** This method returns an observable that ad ...

Modify the color of Material UI's Select Component's IconComponent

Currently in my project, I am utilizing MUI's Select Component with the LanguageIcon as the designated IconComponent. My goal is to change the color of this icon from black (default) to white, but I have been unsuccessful in my attempts. I attempte ...

Managing JSON data retrieval and manipulation techniques

My code is set up to display the image, title, and summary for all entries in a JSON file. However, I only want to display the image, title, and summary for the first entry, and only show the title for the rest of the entries. Please advise. <html> ...