Exploring API information in Ionic 4

Looking to retrieve data from the API, specifically using PHP on the backend. While I can access the data successfully, I'm running into an issue with *ngFor and the search bar functionality. The search button only appears when the input in the search bar matches existing data in the database. This means that upon visiting the website, the search button is not visible until a valid input is entered.

Displayed below is the HTML code for the home page:

<ion-grid >
        <ion-row >

            <ion-col size-xs="12" size-sm="12" size-md="8" size-lg="8">
                <ion-searchbar placeholder="Restaurant" [(ngModel)]="searchTermName" (ionChange)="searchName($event)"></ion-searchbar>
            </ion-col>

        </ion-row>
    </ion-grid>

    <div class="btn" *ngFor="let item of (results | async)">
            <ion-button [routerLink]="['/', 'details', item.reid]" color="primary" fill="solid">
                Search
            </ion-button>
        </div>

    </div>

The TypeScript code for the home page is as follows:

searchName() {
    this.results = this.userService.getName(this.searchTermName);
    console.log(this.results);
  }

Lastly, here is the user service file:

 getName(name1) {
    return this.http.get('http://127.0.0.1:8000/searchRestaurantByName', {headers: {name: name1}}).pipe(
        map(name => {
            console.log('RAW: ', name1);
            return name;
        })
    );
  }

'asd' represents a restaurant stored in the database. https://i.sstatic.net/KUJMj.png

Why does the search button not appear when no text is typed? https://i.sstatic.net/rf9SK.png

Answer №1

Home.ts

updateName() {
   this.userService.fetchName(this.updatedTermName).subscribe((result) => {
    console.log(result);
})

Revise your coding technique, ensure to maintain subscription until receiving response from API.

Answer №2

Displaying the button only when a result is available is key. To implement this, consider adjusting your code as shown below. Whenever the searchbar value changes, call for names from the userService. As soon as results are returned, an item will appear beneath the searchbar.

The search function does not necessarily require a button since it triggers upon searchbar value change. However, if you prefer a button, you can remove the ionChange event and capture the value when clicking the search button instead.

This example serves to illustrate one method of achieving your objective. Feel free to tailor it to suit your specific requirements or explore alternative approaches.

<ion-grid>
  <ion-row>
    <ion-col size-xs="12" size-sm="12" size-md="8" size-lg="8">
      <ion-searchbar placeholder="Restaurant" (ionChange)="searchName($event.target.value)"></ion-searchbar>
    </ion-col>
  </ion-row>
  <ion-row>
    <ion-col>
      <ion-item routerLink="['/', 'details', item.reid]" *ngFor="let item of (results | async)">
        {{ item.name }}
      </ion-item>
    </ion-col>
  </ion-row>
</ion-grid>
searchName(searchValue: string) {
  this.userService.getName(searchValue).subscribe((result: object) => {
    this.users = result;
  });
}

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 issue of the background image not updating with jQuery persists in Internet Explorer 11

Hello everyone, I am facing an issue where I am trying to change the background image of a div using jQuery on click. The code I have written works perfectly on all browsers except for IE. Can someone please provide me with some guidance or help on how to ...

Firebase: Linking a child key from table to another table

Just started working with firebase database and I could use some assistance with mapping to two tables. I have two tables, robots and templates. The template key is assigned to a child node under the robots table. View tables In the robots table, I would ...

Link the input's name to the parent's index in JavaScript

Can a relationship be established between the input element name and its parent index (div) in a way that the input name automatically changes whenever the div index changes? Imagine something like the following: <div> <input type="text" name=" ...

Angular 2: Successfully invoking a component and receiving the parameter is a one-time deal

In my code, I have set up a route like this: { path: 'manageagreements', component: ManageagreementsComponent, children: [ { path: 'editagreement/:agreement', component: EditagreementComponent }, ] ...

What is the best way to transform a Ruby hash into a JavaScript object while maintaining unquoted values?

Is there a way to display a Ruby hash as a JS object without quotes for certain values in the hash, essentially as JS code? For instance, consider the following Ruby code: { foo: proc { 'someJavascriptFn()' } }.to_json How can I have the JS out ...

Should I fork and customize npm package: Source or Distribution? How to handle the distribution files?

Currently, I am in the process of developing a VueJS web application. Within this project, there is a module that utilizes a wrapper for a JavaScript library obtained through npm and designed to seamlessly integrate with VueJS. However, it doesn't com ...

When attempting to access the .nativeElement of an input using @ViewChild, the result is 'undefined' rather than the expected value

In my angular2 project, I created a form with the following code: import {Component, ElementRef, ViewChild, AfterViewInit} from "angular2/core"; import {Observable} from "rxjs/Rx"; import {ControlGroup, Control, Validators, FormBuilder} from "angular2/com ...

Exploring the art of manipulating HTML code using JavaScript

I am looking to implement a specific change using JavaScript: <input id="innn" value="" /> to: <input id="innn" value="SOME_VALUE" /> I attempted the following methods: document.getElementById("innn").setAttribute("value", "189"); and als ...

Encountering a sort error in Angular 8 when attempting to sort an Observable

I am struggling to organize an observable that is retrieved from a service using http.get. I have attempted to sort the data both from the service and in the component after subscribing. However, I keep encountering the error "Sort is not a function". As ...

Troubleshooting a malfunctioning Highcharts yAxis maximum setting

Can someone explain why the yAxis is still labeled up to 15 when the max value is set to 14? I've tried adjusting the startOnTick and maxPadding properties with no success. Here's the link to the code. $(function () { $('#container&apo ...

Error TS2349: The function cannot be called as it does not have a defined call signature. The type 'typeof renderIf' does not have any compatible call signatures

Based on the starter template found at https://github.com/react-native-training/reactxp-starter, I am just starting out with TypeScript! The issue seems to be related to the type in the renderIf function. I'm unsure where exactly the type should be s ...

Add a new sibling item to Angular-UI-tree

I am trying to add a sibling item to a tree when clicked in angular-ui-tree (https://github.com/angular-ui-tree/angular-ui-tree) Here is an example of what I currently have: <item><input value"item A #1"><button>insert under</button& ...

Utilizing Bootstrap Modal to Upload an Image

I'm facing an issue with uploading an image using a Bootstrap modal. The problem I encounter is that even after selecting an image, I continue to receive the validation error message "Your upload form is empty". Below is the script for my form in the ...

Simultaneously activate the 'onClick' and 'onClientClick' events on an ASP button using JavaScript

I have encountered an ASP button while working on existing code that has both onClick and onClientClick events attached to it. My goal is to trigger both events by generating a click event from an external Javascript file. The line of code I am using for ...

Problems encountered when attempting to create a link between two nodes on a force-directed graph using a mouse click

I'm currently working on creating an interactive graph where users can click on two nodes to establish a link between them (which can be removed later). My approach was inspired by Mike Bostock's example at: https://bl.ocks.org/mbostock/1095795 ...

Prevent selection of rows in the initial column of DataTables

I am working on a basic datable, the code can be found here JS: var dataSet = [ ["data/rennes/", "Rennes", "rennes.map"], ["data/nantes/", "Nantes", "nantes.map"], ["data/tours/", "Tours", "tours.map"], ["data/bordeaux/", "Bordeaux", ...

I am encountering some difficulties with the functionality of the angularjs dialog

I've been attempting to integrate an AngularJS dialog feature into my application by following the examples provided on material.angularjs.org. However, despite copying everything accurately, I am unable to get it to function. Can anyone help identify ...

Is there a way to improve the efficiency of this jQuery function that toggles the image source?

I have implemented a functionality that seems to work, but I'm unsure if it's the most efficient solution. I couldn't find a ready-made 'copy-paste' solution online, so I ended up writing this code myself. I am sticking with the &l ...

Is it possible to retrieve all data from the Google translation API?

In my React app, the main component contains this function: componentDidMount(){ const land = ["Afrikaans", "Albanian", "Amharic", "Arabic", "Armenian", "Assamese", "Aymara", &qu ...

Adding properties to React Component

Due to security reasons, I am required to update the ant design library in my codebase from version 3 to 4. In the past, this was how I used the icon: import { Icon } from 'antd'; const Demo = () => ( <div> <Icon type="smile" ...