Shaik
Shaik

Reputation: 296

fetching and displaying the backend json data as dropdown in an Ionic project

Iam working in an ionic project, where my requirement is to get the backend json data through an api call and display the json content as dropdown in front end. below is the api call code,json format and code i tried.

Broker api call

http://example.com/broker/get-user-names

backend Json data:

{
    "USER_NAME": "John",
    "USER_COUNTRY": "USA"
},


{
    "USER_NAME": "Smith",
    "USER_COUNTRY": "Canada"
},


 {
    "USER_NAME": "Peter",
    "USER_COUNTRY": "Russia"
},

I wanted to create a dropdown where i want to get all the usernames in dropdwon to select, i have created a method in .ts files, below the method

 getUserNames() {
this.apiService.getUserNames(this.apiService.loggedInUser.value.id).then(
  res => {
     this.userNames= res;
     alert(JSON.stringify(this.userNames));

  },
  err => {
    alert(JSON.stringify(err))
  }
)
}

In .html file

  <ion-select placeholder="Select One">

          <ion-select-option selected="true" >{{userNames.USER_NAME}}-</ion-select-option>

 </ion-select>

But its displaying only the first user name i.e JOHN in my case as json data contains john as first username.

How can i do to display all the usernames as dropdowns from the backend json data.

please help me on this , i got struck in this from last 1 week.

thanks

Upvotes: 0

Views: 576

Answers (1)

Nicholas K
Nicholas K

Reputation: 15433

Provided this.userNames is an array, use:

<ion-select-option *ngFor="let user of userNames">{{user.USER_NAME}}-</ion-select-option>

.ts

Create an array to hold the data you get from the API

userNames = [];

now in the subscription block:

getUserNames() {
   this.apiService.getUserNames(this.apiService.loggedInUser.value.id)
     .subscribe(res => {
        this.userNames= res;
        alert(JSON.stringify(this.userNames)); 
     },
     err => {
       alert(JSON.stringify(err))
     }
   )
}

Upvotes: 1

Related Questions