Discover how to retrieve service response data from an API and populate it into the Select Option with Angular 2

Api.services.ts

 getListOfNames() {
     return this.http.get(this.BaseURL + 'welcome/getnama')
            .pipe(map(response => {
                 return response;
            }));
 }
 

After making the API call, I receive the following response:

{
"status": "OK",
"Output": [
    {
        "id_pemborong": "1569079912",
        "nama": "ayub"
    },
    {
        "id_pemborong": "1569125109",
        "nama": "Hartono"
    },
    {
        "id_pemborong": "1569319859",
        "nama": "agus"
    },
    {
        "id_pemborong": "1569416787",
        "nama": "joko"
    }
   ]
 }

I am looking for guidance on how to bind this response to a Select Option in Angular. Can someone help me with this?

Answer №1

procedure

fetchNames() {
    return this.http.get(this.BaseURL + 'welcome/getnama')
}

next, you should subscribe to it within your component

//declare a variable
NameList:any[]=[];

// replace service with the name of your service
this.service.function.subscribe(data => this.NameList = data);

and in the Template

<select  [(ngModel)]="selected" (change)="onChange($event)">
<option [label] ="name" *ngFor="let item of NameList" [selected]="selected" 
  [value]="name">{{name}}
</option>
</select>

Answer №2

Your map function is not working correctly in your code. To fix this, you should map the response to the Output property and then subscribe to the Observable to retrieve the value.

api.service.ts

listNama() {
    return this.http.get(this.BaseURL + 'welcome/getnama').pipe(
        map(response => response.Output)
    );
}

Next, make sure to subscribe to the Observable in your component:

import ApiService from 'path/to/api/service';
...

    namaList: Nama[];

    constructor(private apiService: ApiService) { }

    ngOnInit() {
        this.service.listNama().subscribe(data => {
            this.namaList = data;
        });
    }

You'll also need to define a type for the data received, which can be done using the Nama interface:

export interface Nama = {
    id_pemborong: string;
    nama: string;
}

Lastly, use the namaList array in your HTML template to display the list in a dropdown menu:

<select>
    <option *ngFor="let item of namaList" [value]="item.id_pemborong">{{item.nama}}</option>
</select>

Answer №3

Ts

    MyNameList:any[]=[];
    displayNames() {
    return this.http.get(this.BaseURL + 'welcome/getnama')
      .pipe(map(response => {
      this.MyNameList= response.Output;
      }));
     }

Html

    <select  [(ngModel)]="selected" (change)="onChange($event)">
       <option [label] ="name" *ngFor="let item of MyNameList" [selected]="selected" [value]="name">
          {{name}}
       </option>
    </select>

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

javascript get the value of the text field

Is there a way to calculate even and odd numbers using a text field for entering the range of values and a select tag to choose between even and odd? How can I retrieve the value from the text field in order to pass it to the calculation function? Custom ...

Unable to make a POST request to the GitHub v3 API

I'm attempting to generate a public gist using JavaScript without any authentication - all purely client-side. var gist = { "description": "test", "public": true, "files": { "test.txt": { "content": "contents" ...

Each time I attempt to update my profile on the web application, I receive this notification

Working on creating a web app using react, redux, and node for managing profile data. I have a function that controls both creation and editing of profiles. The creation works fine, but I encounter an error message when trying to edit. I've reviewed m ...

Children must be matched to the route before navigating to it

Hello there! I'm having trouble understanding how to navigate new routes with children in Angular 2 rc 4. I'm trying to route to the TestComponent, which has a child, but I keep getting an error message saying "cannot match any route 'test&a ...

The render properties are not compatible with each other

I am currently using ReactQuill as a component, but I encounter this error when implementing it with Typescript. Do you have any suggestions on how to resolve this issue? The JSX element type 'ReactQuill' is not recognized as a constructor fun ...

Updating visual appearance with button clicks and unclicks

Is there a way to dynamically update the button image while clicking on it? This is what I have tried: $('.gamebox_minimap_plus').click(function() { $(this).css("background-image","url('gfx/plus2.png')"); }); The image ch ...

What is the process for using AJAX and PHP to upload an image file?

I'm facing an issue where I want to insert an uploaded image into a database with user details for a profile picture. The output I receive currently shows {"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}. How can th ...

Encountering an error while trying to import GraphQL resolvers and schema

Upon attempting to start the server with the following setup, an error is encountered: Error: "createUser" defined in resolvers, but has an invalid value "function (userInput) {... The resolver's value must be of type object. index.ts const schema ...

Enhancing jQuery Component while making an Ajax request

When a user clicks a button, I am making an ajax call to send out multiple emails. My goal is to update a "Please wait..." div before and after the call with status updates, as well as report any errors that may occur. However, I have encountered an issue ...

Accessing CouchDB using AngularJS requires users to sign in, with the authentication cookie only being sent to the `/_

Check out my previous posts on this topic here: 1, 2 I currently have an AngularJS app with two controllers. The first one interacts with CouchDB documents, while the second handles sign-in requests to example.com/demo/_session. Upon opening the applicat ...

There is no 'next' property available

export function handleFiles(){ let files = retrieveFiles(); files.next(); } export function* retrieveFiles(){ for(var i=0;i<10;i++){ yield i; } } while experimenting with generators in T ...

Encourage users to activate the physical web feature in compatible web browsers

Is it possible to use JavaScript to encourage users to activate the physical web (and thus BlueTooth), similar to how APIs like "getUserMedia()" prompt users? UPDATE: Given that this technology is still in its early stages and not extensively supported, t ...

I'm looking for a way to send a value to my component when the onBlur event is triggered on a PrimeNG autocomplete textbox. Any

I'm currently utilizing the PrimeNG autocomplete textbox. How can I pass a value to my component on the onBlur event? Template <p-autoComplete (ngModelChange)="orguser.userid = $target.value" class="ui-autocomplete autocomplete" [suggestions]="r ...

Is it possible to perform a PHP redirect after the headers have been

I am encountering an issue with a function that needs to redirect the page once a variable is set. The challenge arises from the fact that this function is located at the bottom of the PHP page. As a result, I have already displayed a significant amount ...

Update a specific form data field within an Angular application

I recently encountered a situation where I had an angular form with 9 fields and submitted it to the server using a post request. However, I realized that I had only filled in values for 8 fields while leaving one as null. Now, in a new component, I am w ...

Logging to the console using an If/Else statement, with the Else block containing code that

I'm encountering a peculiar issue with my If statement. I'm modifying the state (true/false) of an object based on onMouseEnter and onMouseLeave. I can execute the code when it's true, but if I include any code in the else statement, it ma ...

Is there a way to ensure an ajax call finishes executing without relying on 'async: false' or callbacks?

In my view, I have implemented a TypeScript code defining a KnockoutJS binding handler for a clickable element as shown below: module MyModule { export interface ICopyButtonParams { dataUrl: string; } ko.bindingHandlers.copyButton = { ...

Tips for migrating an AngularJS application to Angular

My current project involves implementing a basic search function using AngularJS (link). I want to integrate this feature into an existing Angular application. To do this, I created a new Angular app and transferred the view to app.component.html. <hea ...

Utilizing Angular 2 for Displaying SVG Information

I am facing an issue with my angular application where I need to display product information in a SVG image obtained from a service in JSON format. Despite trying different methods, I have been unsuccessful in rendering the image on the HTML template. Att ...

Ensure to check the input file for null values before proceeding

My task involves working with an input file: Razor: @Html.TextBox("archivo", "", new { type = "file",id = "archivo" } Html: <input id="archivo" name="archivo" type="file" value=""> I am trying to detect if the value of the input is null when a b ...