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>