I'm trying to show the data of this API https://swapi.dev/api/people/
{
"results": [
{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male",
},
]
}
but I always get this error :
How to show it like name and then when someone presses the button to character detail page that shows all detail of the API data on Angular? Thank you!
actor.service
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ActorService {
apiUrl = 'https://swapi.dev/api/people/'
constructor(private http: HttpClient) { }
tester(){
this.http
.get('https://swapi.dev/api/people/')
.subscribe(data => {
console.log(data);
})
}
getActors(){
return this.http.get(`${this.apiUrl}`);
}
getActor(name: string){
return this.http.get(`${this.apiUrl}/${name}?per_page=10`);
}
}
actor-list.component
import { Component, OnInit } from '@angular/core';
import { ActorService } from 'src/app/core/services/actor.service';
@Component({
selector: 'app-actor-list',
template: `
<section class="section">
<div class="container">
<div class="columns is-multiline" *ngIf="actors">
<div class="column is-4" *ngFor="let actor of actors | async">
{{ actor.results.name }}
<div class="card">
<div class="card-content">
<a routerLink="/users/{{ actor.results.name }}">{{ actor.results.name }}</a>
</div>
</div>
</div>
</div>
</div>
</section>
`,
styles: [
]
})
export class ActorListComponent implements OnInit {
actors;
constructor(private actorService: ActorService) { }
ngOnInit() {
this.actors = this.actorService.getActors()
}
}
actor-single.component
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ActorService } from 'src/app/core/services/actor.service';
@Component({
selector: 'app-actor-single',
template: `
<section class="section">
<div class="container">
<div class="card" *ngIf="actor">
<h2>{{ actor.results.name }}</h2>
</div>
</div>
</section>
`,
styles: [
]
})
export class ActorSingleComponent implements OnInit {
actor
constructor( private actorService: ActorService, private route: ActivatedRoute) { }
ngOnInit(): void {
this.route.params.subscribe(params => {
const actorname = params['actorname'];
this.actorService
.getActor(actorname)
.subscribe(actor => this.actor = actor)
});
}
}
CodePudding user response:
I think you misunderstood the structure of the api response. There is no field result
in a single actor. So actor name should be
<h2>{{ actor.name }}</h2>
and response is an object with all actors in results
property. So you can iterate through actors like this
<div class="column is-4" *ngFor="let actor of (actors | async)?.results">
CodePudding user response:
I tried to reproduce your source code, you used wrong property
for object.
It should be *ngFor="let actor of actors.results"
and change from actor.results.name
to actor.name