1

I have just started learning Angular and I am lost for this first application. I'm looking to pass an ID to a child component so that it executes a request to an API to retrieve data.

Here is my code:

Child component:

@Component({
  selector: 'app-set-content',
  templateUrl: './set-content.component.html',
  styleUrls: ['./set-content.component.css']
})
export class SetContentComponent implements OnInit {
  @Input() setId;
  equipments;

  constructor(
    private http: HttpClient
  ) {
    this.equipments = this.http.get('https://myapi.com/sets/'+this.setId+'/details')
   }

  ngOnInit() {
  }

}

HTML Code for the Parent component:

<div class="card" *ngFor="let set of sets | async">
    <div class="card-header">
            {{ set.name }}
    </div>

    <div class="card-block">
        <div class="card-text">
                <app-set-content [setId]="set._id">
                </app-set-content>
        </div>
    </div>

</div>

However, in my browser console, I see that the ID passed to the child component is "undefined".

GET https://myapi.com/sets/undefined/details 400 (Bad Request)

I tried to pass an arbitrary parameter like "1" but I get the same error

mamenejr
  • 305
  • 9
  • 17
  • `Input` variables wont be defined during the component instantiation. See https://angular.io/guide/lifecycle-hooks – Jota.Toledo Jul 18 '19 at 12:07

1 Answers1

0

Try to call in ngOnInit method because @Input parameters will be initialized ligecycle called ngOnInit:

ngOnInit() {
    this.equipments = this.http.get('https://myapi.com/sets/'+this.setId+'/details')
}
StepUp
  • 36,391
  • 15
  • 88
  • 148