Невозможно отобразить элемент списка - PullRequest
1 голос
/ 19 марта 2020

Я новичок в Angular, и я создаю простое одностраничное приложение рецептов еды. Я пытаюсь отобразить список рецептов, из которых пользователь может выбирать, но по какой-то причине он не прочитал свойство объекта рецепта в массиве рецептов. При перекомпиляции продолжает появляться сообщение об ошибке, в котором говорится, что «Свойство name» не существует для типа «Recipe []».

Вот рецепты. html file:

   <link href="https://fonts.googleapis.com/css?family=Lobster&display=swap" rel="stylesheet">

    <h2>Recipes</h2>
<div *ngFor="let recipeEl of recipe">
    <a 
    href="#"
    class="list-group-item clearfix">
    <div class="pull-left">
        <h4 class="list-group-item-heading">{{ recipeEl.name }}</h4>
        <p class="list-group-item-text">{{ recipeEl.description }}</p>
    </div>
    <span class="pull-right">
        <img 
        [src]="recipeEl.imagePath" 
        alt="{{ recipeEl.name }}"
        class="img-responsive"
        style="max-height: 50px">
    </span>
</a>
</div>

Вот файл recipes.component.ts:

import { Component, OnInit, Input } from '@angular/core';
import { Recipe } from './recipes.model';
import { Recipeservice } from './recipes.service';

@Component({
  selector: 'app-recipes',
  templateUrl: './recipes.component.html',
  styleUrls: ['./recipes.component.css'],
})
export class RecipesComponent implements OnInit {
  @Input() recipe: Recipe[];

  constructor(private recipeService: Recipeservice) {}

  ngOnInit() {
    this.recipe = this.recipeService.getRecipes();
  }

}

Вот файл recipes.model.ts:

import {Ingredient} из "../shared/ingredient.model ";

export class Recipe { 
  public name: string;
  public description: string;
  public imagePath: string;
  public ingredients: Ingredient[];

  constructor(name: string, desc: string, imagePath: string, ingredients: Ingredient[]) {
    this.name = name;
    this.description = desc;
    this.imagePath = imagePath;
    this.ingredients = ingredients;
  }
}

Вот файл recipes.service.ts:

import { Recipe } from './recipes.model';
import { Ingredient } from '../shared/ingredient.model';
import { Injectable } from '@angular/core';

@Injectable()
export class Recipeservice {

    private recipes: Recipe[] = [
        new Recipe('Spaghetti Carbonara', 'Authentic Italian Carbonara', 'https://cdn.pixabay.com/photo/2015/04/08/13/13/pasta-712664_960_720.jpg', [
            new Ingredient('Spaghetti', 500),
            new Ingredient('Lardons', 20),
            new Ingredient('egg', 4),
            new Ingredient('parmesan', 100),
            new Ingredient('Garlic', 1),
            new Ingredient('Olive Oil', 50)
        ])
    ]

        getRecipes() {
            return this.recipes.slice();
        }

}

Ответы [ 2 ]

1 голос
/ 19 марта 2020

Может быть, перебрать ваш массив с * ngFor = "let recipe of recipes " следующим образом:

<div *ngFor="let recipe of recipes">
   <a href="#"class="list-group-item clearfix">
    <div class="pull-left">
       <h4 class="list-group-item-heading">{{ recipe.name }}</h4>
        <p class="list-group-item-text">{{ recipe.description }}</p>
    </div>
   <span class="pull-right">
    <img 
    [src]="recipe.imagePath" 
    alt="{{ recipe.name }}"
    class="img-responsive"
    style="max-height: 50px">
   </span>
   </a>
</div
1 голос
/ 19 марта 2020

Проблема в том, что Recipe - это массив, и вы его итерируете, поэтому:

<div *ngFor="let element of recipe" class="pull-left">
        <h4 class="list-group-item-heading">{{ element.name }}</h4>
        <p class="list-group-item-text">{{ element.description }}</p>
 </div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...