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

Displaying events on FullCalendar using a list of dates separated by commas from a MySQL database table row

My goal is to display multiple events based on dates from the same row of the table in the database, separated by commas as shown in the image below: Link to Database Table Image Below is my PHP/WordPress code that retrieves results from the database: ...

What situations call for the use of 'import * as' in TypeScript?

Attempting to construct a cognitive framework for understanding the functionality of import * as Blah. Take, for instance: import * as StackTrace from 'stacktrace-js'; How does this operation function and in what scenarios should we utilize imp ...

Angular2 asynchronous operations in a shared service encountering a JSON error starting at index 0

My shared-service for calling an API is giving me an error message Unexpected token < in JSON at position 0. The issue seems to be related to async requests, as the data is not always available leading to this error. The error log is indicating a probl ...

Combining duplicate keys in JSON aggregation using MySQL's many-to-many relationship

I'm facing a challenge with returning a JSON representation of a many-many join. My initial plan was to encode the columns returned in the following unique JSON format { "dog": [ "duke" ], "location": [ &quo ...

Issue R10 (Start-up delay) -> Failure of web application to connect to $PORT in the given 60 seconds after being launched (Angular)

I am currently in the process of building an Angular 7 application and attempting to connect it to Heroku (I am fairly new to using Heroku). Upon trying to run the application on Heroku, I encountered the following error: https://i.stack.imgur.com/ySmJw.p ...

Working with dual generic parameters in a function

Here is a function I am using: bind<T, K extends keyof T>( data: T[], bindedData: T[], key: K, newKey: string ) { } I'm trying to use two generic parameters, but my attempt here did not work: bind<T, K extends keyof T> ...

Determine if a condition is met in Firebase Observable using scan() and return the

Within Firebase, I have objects for articles structured like this: articles UNIQUE_KEY title: 'Some title' validUntil: '2017-09-29T21:00:00.000Z' UNIQUE_KEY title: 'Other title' validUntil: '2017-10-29T21:00:00 ...

Utilizing Angular 2's ngModel feature for dynamic objects and properties

Within my TypeScript file, I am dynamically generating properties on the object named selectedValsObj in the following manner: private selectValsObj: any = {}; setSelectedValsObj(sectionsArr) { sectionsArr.forEach(section => { section.questions. ...

Unable to simulate a returned value from an import in Jest

Within my module, I have a function called shuffle<T>(a: T[]): T[] that is exported by the random module. While testing two methods in another class that rely on this function, I need to mock it. Here's how I attempted to do so: jest.mock(' ...

Ways to protect the URL link for attachments obtained from cloud services

I have created an Angular form that allows users to upload attachments. Once uploaded, the attachments are securely stored in an Azure Storage Account. Upon successful upload, a unique URL for the attachment is generated and returned. However, the curren ...

Jasmine has detected an undefined dependency

Testing out the following code: constructor(drawingService: DrawingService) { super(drawingService); //... } private writeOnCanvas(): void { this.drawingService.clearCanvas(this.drawingService.previewCtx); this.drawing ...

Guidelines on fetching API data in React JS

When attempting to retrieve data from the OpenWeather API, I encountered an issue. The API's response is expected to be in JSON format, but instead, I received an error message: SyntaxError: Unexpected token < in JSON at position 0 useEffect(() =& ...

Tips for refining TypeScript discriminated unions by using discriminators that are only partially known?

Currently in the process of developing a React hook to abstract state for different features sharing common function arguments, while also having specific feature-related arguments that should be required or disallowed based on the enabled features. The ho ...

Angular2 - Creating PDF documents from HTML content with jspdf

For my current project, I am in need of generating a PDF of the page that the user is currently viewing. To accomplish this task, I have decided to utilize jspdf. Since I have HTML content that needs to be converted into a PDF format, I will make use of th ...

Using Powershell to Generate a Simple JSON Document

I'm new to working with JSON and could use some assistance in creating a basic JSON file. Here is the code I have so far: $fruits = lookup-fruit | ConvertFrom-Json foreach ($fruit in $fruits) { $fruit.name $fruit.color $fruit.origin } My goa ...

The successful JSON response in an Ajax request is not functioning as expected

I've set up a data table that allows users to add rows by clicking the "plus" button. This triggers an ajax request to a URL with the rowId as a parameter (which corresponds to the specific row where the button was clicked). I expect to receive a JSON ...

Receiving a notification when attempting to log in with incorrect credentials

I am currently working on an Angular login page implementation using a username and password setup. When the user enters incorrect credentials, I want to display an alert message indicating the same. Here is the HTML code snippet for the form: <form [f ...

Can the PrimeNG p-fileUpload component be configured to launch from a specific directory?

Utilizing the PrimeNG p-fileUpload component for file uploads. Looking to customize the default folder that opens when the select file button is clicked. Would like it to open in a specific location such as Desktop or Videos. Is there a method to achieve ...

What changes occur to the files in an Angular project, specifically Angular 8, when the npm install command is run?

When running "npm install" in an Angular project (specifically angular 8), which files are created or modified? Do I need to delete the package.lock.json file along with the node_modules folder when updating something in the package.json file? Will npm i ...

Typescript type/object's conditional property feature

Imagine having a recipe ingredient type structured like this export type RecipeIngredient = { name: string; amount: Number | string; unit: "grams" | "milliliters" | "custom"; }; To illustrate const apples: RecipeIngredient = { name: 'apples&a ...