这是我使用Angular2的第一个项目。我在我的角度fron中没有使用任何文件路径。我构建了一个API来从laravel 5.4 backEnd获取数据与json数组对象中的服务:
getFoodsByCat(id :number): Observable<any> {
return this.http.get('http://livrer/api/menu/' +id)
.map(
(response: Response) => { return response.json().foods;
}
);}
在我的组件中,我使用这样的服务:
import {Response} from '@angular/http';
import { Food } from "./food.interface";
import { FoodService } from "./food.service";
export class FoodsComponent implements OnInit {
@Input() food : Food ;
foods: Food[];
constructor(private foodService: FoodService ) { }
ngOnInit() {
onGetFoodsByCategorie( id){
this.foodService.getFoodsByCat(id)
.subscribe(
(foods: Food[])=> this.foods = foods,
(error : Response)=> console.log(error)
);
} }
此服务函数获取json响应,如下所示:
{"foods":[{"id":10,"designation":"pannin fromage","description":"
Pannini fromage cornichon<\/p>","prix":25,"created_at":"2017-03-11 17:59:34","updated_at":"2017-03-11 ...}]}
在模板中我使用onload循环开始获取数据第一个元素id = 1
<ul class="resp-tabs-list">
<li class="active" (load)="onGetFoodsByCategorie(1)">Panninis</li>
<li (click)="onGetFoodsByCategorie(2)">Somthing</li>
<li (click)="onGetFoodsByCategorie(3)">Sandwichs</li>
<li (click)="onGetFoodsByCategorie(4)">Pizzas</li>
</ul>
<li *ngFor= "let food of foods" [food]="foods">
//some style and data
</li>
我收到此错误:
Error: Template parse errors:
Can't bind to 'food' since it isn't a known property of 'li'. ("
<li *ngFor= "let food of foods" [ERROR ->][food]="foods">
<div class="item">
<div class="thumbnail-menu-modern">
"): FoodsComponent@26:32
答案 0 :(得分:1)
如果要将数据从父组件发送到子组件,请使用@Input。 @Input应该在子组件而不是父组件中设置。
父组件
import {Response} from '@angular/http';
import { Food } from "./food.interface";
import { FoodService } from "./food.service";
export class FoodsComponent implements OnInit {
foods: Food[];
constructor(private foodService: FoodService ) { }
ngOnInit() {
onGetFoodsByCategorie( id){
this.foodService.getFoodsByCat(id)
.subscribe(
(foods: Food[])=> this.foods = foods,
(error : Response)=> console.log(error)
);
}}
子组件
import { Component, Input } from '@angular/core';
@Component({
selector: 'child-comp',
template: '<h3>"{{food}}"</h3>'
})
export class ChildComponent {
private _food = '';
@Input()
set food(food: string) {
this._food = (name && food.trim()) || '<no name set>';
}
get food(): string { return this._food; }
}
并在父模板中使用子组件选择器,如下所示。请注意,如果您想要发送阵列中的每种食物,请使用食物而不是食物。我下面的示例将每个食物发送到要显示的子元素。如果您想将食物阵列发送给孩子,请使用<child-comp [food]="foods"></child-comp>
<ul class="resp-tabs-list">
<li class="active" (load)="onGetFoodsByCategorie(1)">Panninis</li>
<li (click)="onGetFoodsByCategorie(2)">Somthing</li>
<li (click)="onGetFoodsByCategorie(3)">Sandwichs</li>
<li (click)="onGetFoodsByCategorie(4)">Pizzas</li>
</ul>
<child-comp *ngFor= "let food of foods" [food]="food"></child-comp>