简体   繁体   中英

Angular 9 consume REST API

i'm new to Angular and i'd like to use it for my front end. i have a REST API in spring which gives the below Json content, My problem is that i manage to display the products using a *ngFor, but i would like to display for each product his category.

I looked up on internet but it only explains how to show a simple entity, not the href links value. thanks for your help

{
  "_embedded" : {
    "products" : [ {
      "id" : 4,
      "name" : "lKVOJRjKir",
      "description" : null,
      "currentPrice" : 405.0,
      "promotion" : true,
      "selected" : true,
      "available" : false,
      "photoName" : "unknown.jpeg",
      "quantity" : 1,
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/products/4"
        },
        "product" : {
          "href" : "http://localhost:8080/products/4"
        },
        "category" : {
          "href" : "http://localhost:8080/products/4/category"
        }
      }

this is my service:

 private getProducts(url) {
    this.catalogueService.getResource(url)
      .subscribe(data => {
        this.products = data;
      }, error => {
        console.log(error);
      })
  }

this is my html file and what i've tried:

<div class="col-md-4" *ngFor="let p of products._embedded.products" >
     <div class="card" >
       <div class="card-header">{{p.name}}</div>
       <div>Price : {{p.currentPrice|number:'0.2'}}</div>
       <div>{{p.description}}</div>
       <div>Selected: {{p.selected}}</div>
       <div> Category: {{p.category.name}}</div>  // not working

There is no category key in the above json object. If it is not returned for every product json object. You can go with safe operator in your html. {{p?.category?.name}}

just to close the subject i found a solution which is to expose the category fields using: https://docs.spring.io/spring-data/rest/docs/3.1.x/reference/html/#projections-excerpts.excerpting-commonly-accessed-data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM