Ad

Inputted Number Will Add To API URL Key Value Via Passing Variable From Page.html To Services.ts

I'm new in Ionic, Angular and Typescript, is it possible for the inputted number will add to the API URL as one of the key value? I followed this guide under Key event filtering (with key.enter)

Here's my page.html

    <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>

and here's my example API URL.

'https://myapi.com/FoodDeliveryTracking?&userName=myuser&password=mypass&MyNumber='+myNum

Here's my page.ts

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


orders= [];
ionViewWillEnter() {
  // Load the data
  this.dataService.getRemoteData(this.myNum).subscribe( //comment this if you will use local data
    data => {
      // Takes data into in single Array and print 
      this.orders = data.output.Result.FoodOrderTracking;
    },
    err => {
      // Set the error information to display in the template
      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)
    })
  }   

Here's my data.services.ts which is for fetching the data from my 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 = ''; // <-- Enter your own key here!



    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});
    }


}

How can I pass a variable from my input on my page.html to the services.ts? Is it possible? So that in my services.ts

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

Ad

Answer

Try this

Use databinding in your html template

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

component.ts

Modify onEnter on your page to call the service

onEnter () {

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

dataservice.ts

Just use base url for API

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

Modify getRemoteData to use HttpParams to send 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));
}

Here is a demo code on stackblitz. Of cours the http request does not succeed since the api url does not exist, but you can see in the network debugger that it's sending all parameters

Ad
source: stackoverflow.com
Ad