Using the map function, in what way might you locate a distinct value from every individual object within an array of objects?

I've recently started working with Angular and I'm trying to use an API like to fetch the names of each person from a list of people objects and display them in a dropdown menu. For this particular assignment, I need to utilize .map() to generate the values for the dropdown. I've attempted to refer to the angular documentation but I find myself quite confused and in need of some assistance.

service.ts

import {HttpClient} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class StarwarsService {

  constructor(private http: HttpClient) { }

  getPeoples() {
    return this.http.get('https://swapi.co/api/people/  ');
  }

  getPlanets() {
    return this.http.get('https://swapi.co/api/planets/  ');
  }

  getStarships() {
    return this.http.get('https://swapi.co/api/starships/  ');
  }
}

app.module.ts

import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { BodyComponent } from './body/body.component';
import { FooterComponent } from './footer/footer.component';
import { PlanetsComponent } from './planets/planets.component';
import { StarshipsComponent } from './starships/starships.component';
import { NotFoundComponent } from './not-found/not-found.component';
import {HttpClientModule} from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    BodyComponent,
    FooterComponent,
    PlanetsComponent,
    StarshipsComponent,
    NotFoundComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

body/component.ts

import { StarwarsService } from '../starwars.service';

@Component({
  selector: 'app-body',
  templateUrl: './body.component.html',
  styleUrls: ['./body.component.scss']
})
export class BodyComponent implements OnInit {

  constructor(private starwarsService: StarwarsService) { }

  ngOnInit() {
    this.starwarsService.getPeoples().subscribe(results => {
      console.log(results);

    });
  }

}

body.component.html

<nav class="navbar navbar-default">
  <div class="container-fluid">
  <ul class="nav nav-pills nav-fill">
      <li class="nav-item col-md-3">
          <a href="/people" routerLink="/people" routerLinkActive="active">People</a>
      </li>
      <li class="nav-item col-md-3">
          <a href="/planets" routerLink="/planets" routerLinkActive="active">Planets</a>
      </li>
      <li class="nav-item col-md-3">
          <a href="/starships" routerLink="/starships" routerLinkActive="active">Starships</a>
      </li>
    </ul>
    </div>
</nav>

  <select>
    <option></option>
 </select>

Answer №1

When working with Angular, utilizing structural directives can be incredibly helpful for rendering lists. One key directive to consider is *ngFor. Further details can be found here.

To effectively handle responses from APIs, it's important to store the data in a component property.

import { StarwarsService } from '../starwars.service';

@Component({
  selector: 'app-body',
  templateUrl: './body.component.html',
  styleUrls: ['./body.component.scss']
})
export class BodyComponent implements OnInit {

  peoples: unknown[];

  constructor(private starwarsService: StarwarsService) { }

  ngOnInit() {
    this.starwarsService.getPeoples().subscribe(results => {
      console.log(results);
      this.peoples = results.results;
    });
  }
}

The data retrieved from the API (stored in results) is assigned to the component's this.peoples property for template usage.

In the template, the *ngFor directive can be used to iterate through and display the list of peoples.

<select>
  <option *ngFor="let people of peoples">
    {{people.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

The filter is throwing an error: $scopeProvider is an unknown provider and it is trying to use $scope and transformSensorStatusFilter

marsApp.filter("transformSensorStatus", function($scope) { return function(input, options) { var sensorReading = ( input ? ( input / 1000) : 0); var sensorLowLimit = (options["lowLimit"] ? (options["lowLimit"] / 1000) : 0); var sensorHighL ...

Even if the parameter is not set in the function, it will still function properly

How can I call a function, regardless of whether the parameter is set or not? What is the correct way to achieve this? select(); select($response_message); function select($response_message) { .... } ...

Unable to reference a css class in jQuery for elements generated using jQuery

I am encountering an issue with my jQuery code related to designing a chat application. The problem arises when trying to display the users list received from the backend through ajax in the frontend. Although I can successfully obtain and display the data ...

Retrieve all the data enclosed within the span tags

Assuming there are two instances of tbody on a given page, is it possible to retrieve all the data enclosed within the spans of the second occurrence of tbody as shown below? The unique id's (id=id1, id=id2, etc) can only be found once throughout the ...

How can I show PHP retrieved data in separate text areas?

Struggling to retrieve values from the database? Simply select an employee ID using the 'selectpicker' and watch as the corresponding name and salary are displayed in the textarea. So far, I've managed to set up the following HTML Code: &l ...

Implementing multiple modules within a shared parent route in Angular

Currently, I am seeking a method to load multiple modules under the same path in Angular. Let's say I have three modules: AModule, BModule, and CModule, each with its own RouterModule.forChild call. My goal is to combine these modules under the route ...

What is the most effective way to eliminate landmarks when utilizing the MapKit API on iOS?

Is there a way to conceal local landmarks while exploring a specific area using the Apple Maps API? ...

Having trouble assigning the class property in Angular 5

Upon loading the page, a list of products is retrieved from an external JSON source. Each product in the list has a corresponding BUY button displayed alongside it, with the ID of the respective product assigned to the button. The intention is that when a ...

Modify HTML content according to the response received from the backend

I am trying to dynamically update the text content of an HTML tag based on a response from the backend. My application is running on a Django server where I have a timer in the backend measuring the processing time. I need to send this processing time to t ...

Is it possible for a recursive function in expressjs to return an empty array?

I am working on extracting all child elements from MongoDB using a recursive function. The function loops through all the values and successfully logs them when pushed to an array. However, I am facing an issue where the returned array is empty. This cod ...

I have the capability to show the retrieved data from an API within the input field on Angular 8, along with any console errors that may arise

I have a reactive form set up to fetch data from an API and display it in the input field of my HTML. However, I'm encountering some errors in the console. Can someone help me troubleshoot this issue? Here is the snippet of the HTML code: <form ...

Issues with React and Typescript testing arise from a type error stating "Failed to convert type 'Global & typeof globalThis' to type 'GlobalWithFetchMock'..."

Working with React and Typescript is an exhilarating experience, but it can sometimes lead to perplexing challenges. Recently, all my tests started failing due to a recurring error associated with jest-fetch-mock: > NODE_ENV=test jest FAIL src/store/i ...

Encountering an issue with npm start when attempting to launch the local host server for a React.js project

Encountering an issue with npm start Error message: 'Equipment' is not recognized as a command, operable program or batch file. internal/modules/cjs/loader.js:983 throw err; ^ Error: Module not found 'C:\Users\Home\Deskto ...

How come the interaction between my parent and child components does not create a rendering cycle?

Imagine a scenario where a parent component is responsible for displaying a chart component. The chart component receives time series data and plots it if certain criteria are met. If the data does not meet these criteria, an error message is sent to the p ...

Tips for assigning a class name to a variable element within a react component?

I am interested in dynamically adding classes to an element. While I am familiar with methods using html-dom and passing a JavaScript expression to className, I am seeking a different approach. Is there a way to add classes similar to pushing them to an ar ...

Is there a way to close the menu in react by clicking anywhere on the

Presently, I have a solution to close my topbar menu that involves clicking the menu icon. However, this method is not satisfactory because it only closes the menu when the icon is clicked. I am looking for a way to make the menu close when any area of th ...

Uh-oh! The module "side-channel" cannot be found. An error occurred in the loader with code 936 when trying to run the command "npm start"

During the execution of npm start to view my React app, I encountered the following error: > react-scripts start node:internal/modules/cjs/loader:936 throw err; ^ Error: Cannot find module 'side-channel' Require stack: - C:\Users&bs ...

The microservices system fails to initialize

I've recently delved into the world of microservices, but I've hit a roadblock in my application. app.listen(port) Despite adding .catch() I'm still unable to figure out what's going wrong. The function in question looks like this: nx ...

I rely on Nebular for my Angular application, however, I am looking to make some manual CSS changes that I am having difficulty implementing

While using Nebular for my Angular app, I have run into issues with changing some CSS manually. Specifically, when using nb-select or nb-toggle, I am unable to customize the CSS as desired. Do you have any suggestions to help me with this problem? enter i ...

Having trouble obtaining search parameters in page.tsx with Next.js 13

Currently, I am in the process of developing a Next.js project with the Next 13 page router. I am facing an issue where I need to access the search parameters from the server component. export default async function Home({ params, searchParams, }: { ...