Angular5. Nie mogę wyświetlić zagnieżdzonego objektu w *ngFor

0

Mam problem z wyświetleniem wszystkich produktów znajdujących się w danej kategorii. Gdy komponent się załaduje mam błąd w konsoli chrome:

Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed

Komponent:

export class CategoriesDetailsComponent implements OnInit {
  listCategories:  Categories[] = [];
  constructor(private activatedRoute: ActivatedRoute,
     private productService: CategoriesProductsService) { }

  ngOnInit() {
    this.displayProductsByCategoryId();
  }
  displayProductsByCategoryId() {
    const id = +this.activatedRoute.snapshot.params['id'];
    this.productService.getCategoriesById(id)
    .subscribe((data) => {
      this.listCategories = data;
      console.log(this.listCategories);
    });
}
}

Szablon HTML:

<div class="row">
    <div class="col-sm-4" style="cursor: pointer;" *ngFor="let categories of listCategories " [routerLink]="['/products-details', categories.Id]" >
      <div *ngFor="let product of categories.Product">
        <h3 style="text-align: center">Product Name: {{product.Product.Name}}</h3>
      <img class="img-fluid" src="{{product.Product.Image}}">
      <p style="color: yellow">Price: {{product.Product.Price}}PLN</p>
    </div>
    </div>
  </div>


Klasy Categories i Product:

export class Categories {
  Id: number;
  Name: string;
  Product: Products[];
}
export class Products {
  Id: number;
  Name: string;
  Description: string;
  DetailedDescription: string;
  Price: string;
  IsNewProduct: boolean;
  PromotionalProduct: boolean;
  Image: string;
  CategoryId: number;
}


**Serwis: **

 getCategoriesById(id) {
    return this.http.get<Categories[]>('http://localhost:61085/api/Categories/GetCategoriesById/' + id);
  }

0

categories.Product to array ?

0

A nie ma być tak czasami categories.Products zamiast categories.Product ?

0

W chrome consoli po indexie mam dostęp do właściwości produktu. Zrobiłem tak samo w angularze w *ngfor dodając index, ale dalej wyrzuca ten sam błąd.

<div class="row">
    <div class="col-sm-4" style="cursor: pointer;" *ngFor="let categories of listCategories" [routerLink]="['/products-details', categories.Id]" >
      <div *ngFor="let product of categories.Product; let i=index;  ">
        <h3 style="text-align: center">Product Name: {{product.Product[i].Name }}</h3>
    <img class="img-fluid" src="{{product.Product[i].Image}}">
      <p style="color: yellow">Price: {{product.Product[i].Price}}PLN</p>
    </div>
    </div>
  </div>


1
        <h3 style="text-align: center">Product Name: {{product.Product.Name}}</h3>
      <img class="img-fluid" src="{{product.Product.Image}}">
      <p style="color: yellow">Price: {{product.Product.Price}}PLN</p>

Wydaje mi się, że jesteś za głęboko w tym miejscu. Skoro robisz *ngFor po categories.Product do dlaczego wyciągasz {{ product.Product.Name }}? Powinno być {{ product.Name }}?

A gdybyś zainicjalizował array w klasie?

export class Categories {
  Id: number;
  Name: string;
  Product: Products[] = [];
}

Dało by to coś?

0

Zwrócenie nowej tablicy map() z produktami w serwisie rozwiązało problem.


  getCategoriesById(id) {
    return this.http.get<Categories[]>('http://localhost:61085/api/Categories/GetCategoriesById/' + id)
    .map((data: any) => data.Products );
  }

0

Nie chce tworzyć nowego tematu, wiec się podepnę bo mam podobny problem:
front:
component.html:

<div class="container my-2 mx-auto">
  <div class="row">
    <div *ngFor="let book of books" class="col-md-4 box-shadow my-1">
      <div class="card text-center">
        <div class="card-body">
            <img style="width: 200px; height: 300px" src="{{book.cover}}" class="card-img-top">
            <span class="card-text">
              <h3>
                {{book.title}}
              </h3>
              {{book.authors}}
            </span>

component.ts:

 books;

  ngOnInit() {
this.books = this.booksService.getSharedBooks(number);
}

service.ts

  constructor(private _http: HttpClient) { }

  public books = {data: null};
  
  getSharedBooks(pageNo){
    this.getAllBooks(pageNo);
    return this.books;
  }

  getAllBooks(pageNo: any){
    console.log(pageNo)
    this._http.get(`http://localhost:3000/books?pageNo=${pageNo}&size=9`).subscribe(res => {
      this.books.data = res;
      console.log(res)
    });
  }

z backendu dostaje plik .json takej postaci:

{
    "data": [
        {
            "authors": [
                "Władysław Stanisław Reymont"
            ],
            "_id": "5bfaef94332318353812aeff",
            "kind": "Epika",
            "full_sort_key": "reymont wl~0adysl~0aw stanisl~0aw$dwie wiosny$3651",
            "title": "Dwie wiosny",
            "url": "https://wolnelektury.pl/katalog/lektura/dwie-wiosny/",
            "has_audio": false,
            "cover": "book/cover_thumb/dwie-wiosny_jWDuFKM.jpg",
            "slug": "dwie-wiosny",
            "epoch": "Pozytywizm, Modernizm",
            "href": "https://wolnelektury.pl/api/books/dwie-wiosny/",
            "genre": "Nowela",
            "simple_thumb": "https://wolnelektury.pl/media/book/cover_api_thumb/dwie-wiosny.jpg",
            "cover_color": "#7784e0"
        }
    ]
}

jakiś pomysł lub naprostowanie? .map u mnie nie działa, nawet .pipe(map())
EDIT: Angular 6

1

Pewnie ten sam problem co wyżej
Zamiast:

this.books.data = res;

Zrób:

this.books = res;

Albo

this.books.data = res.data;

1 użytkowników online, w tym zalogowanych: 0, gości: 1