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