Russell
Russell

Reputation: 63

How to pass Id fetched from api to angular method?

I want to be able to display the name of the shop once I have clicked on the shop name from the list. Below is the code I have so far, it is not working! I have tried altering the HTML template, specifically the (code)="" piece. Am I doing something wrong? I have now got it working, but am receiving an error of "Cannot read property 'name' of undefined."

Shops.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-shops',
  templateUrl: './shops.component.html',
  styleUrls: ['./shops.component.css']
})
export class ShopsComponent implements OnInit {
  shops: any;
  shop: any;
  constructor(private http: HttpClient) { }

  ngOnInit() {
    this.getShops();
  }
  getShops() {
    this.http.get('https://localhost:44366/api/shops').subscribe(response => {
      this.shops = response;
    }, error => {
      console.log(error);
    });
  }
  getShop(id: number) {
    this.http.get('https://localhost:44366/api/shops/' + id).subscribe(response => {
      this.shop = response;
    }, error => {
      console.log(error);
    });
  }
}
Shops.html
<ul *ngFor="let s of shops">
  <li><a href="" (click)="getShop(s.id)">{{s.name}}</a></li>
  <li>{{s.address}}</li>
</ul>

<p>{{shop.name}}</p>

Upvotes: 1

Views: 375

Answers (3)

Amit kumar
Amit kumar

Reputation: 6147

Your shop variable don't have any value in initial case. its undefined. so either you assign some value in ngOnInit() part to shop variable or use safe navigation symbol (?)

{{shop?.name}}

<ul *ngFor="let s of shops">
  <li><a href="" (click)="getShop(s.id)">{{s.name}}</a></li>
  <li>{{s.address}}</li>
</ul>

<p>{{shop?.name}}</p>

to check content of your shop variable please use this code

<p>{{shop | json }}

Upvotes: 2

Russell
Russell

Reputation: 63

Seeing as I am receiving a JSON object, I should have initialized my shop variable to type object, to begin with in my ts file.

shop: {};

I then had to go into my HTML template and alter the code a bit

<p>{{shop?.name}}</p>

It appears the correct way of going about this is to create an interface. I will be looking into that solution now.

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222542

Try passing whole Object and use safe navigation operator to display the shop name as it is being retrieved from an asynchronous call

<ul *ngFor="let s of shops">
  <li><a href="" (click)="getShop(s.id)">{{s.name}}</a></li>
  <li>{{s.address}}</li>
</ul>

<p>{{shop?.name}}</p>

anyhow it is always better to create an Interface to deal with objects on the template.

Upvotes: 0

Related Questions