我正在尝试从Firebase中提取数据并将其显示在我的页面上,但嵌入在我的ngFor中的所有内容都没有显示,任何想法为什么?
我的页面目前看起来像这样,但我希望ul中的数据实际显示
店项-list.component.html
<div>
<h1>TEST</h1>
<ul>
<li *ngFor="let shopItem of shopItems">
<div>
<h2>TESTING 2.0</h2>
<h1>{{shopItem.name}}</h1>
<p>{{shopItem.price}}</p>
</div>
</li>
</ul>
</div>
店项-list.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { ShopItem } from '../../models/shopItem';
@Component({
selector: 'app-shop-items-list',
templateUrl: './shop-items-list.component.html',
styleUrls: ['./shop-items-list.component.css']
})
export class ShopItemsListComponent implements OnInit {
@Input()
shopItems: ShopItem[];
constructor() { }
ngOnInit() {
}
}
app.component.html
<input type="text" placeholder="Search..." (keyup)="search(input.value)" #input>
<app-shop-items-list [shopItems]="filteredShopItems"></app-shop-items-list>
app.component.ts
import { Component, OnInit } from '@angular/core';
import {ShopItem} from './models/shopItem';
import {ShopService} from './app.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
allShopItems: ShopItem[];
filteredShopItems: ShopItem[];
constructor(private service: ShopService) {}
ngOnInit() {
this.service.findAllShopItems()
.subscribe(
shopItems => this.allShopItems = this.filteredShopItems = shopItems
);
}
search(search: string) {
this.filteredShopItems = this.allShopItems.filter(shopItem =>
shopItem.name.toLowerCase().includes(search.toLowerCase())
);
}
}
app.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { AngularFireDatabase } from 'angularfire2/database';
import { ShopItem } from './models/shopItem';
@Injectable()
export class ShopService {
constructor(private af: AngularFireDatabase) {}
findAllShopItems(): Observable<ShopItem[]> {
return this.af.list('products').valueChanges().map(ShopItem.fromJsonList);
}
}
shopItem.ts
export class ShopItem {
constructor (
public $key: string,
public filename: string,
public name: string,
public price: number
) {}
static fromJsonList(array): ShopItem[] {
return array.map(ShopItem.fromJson);
}
static fromJson({$key, filename, name, price}): ShopItem {
return new ShopItem(
$key,
filename,
name,
price
);
}
}
答案 0 :(得分:1)
您要将空数组指定给 allShopItems
,而是将其更改为
ngOnInit() {
this.service.findAllShopItems()
.subscribe(
shopItems => this.allShopItems = shopItems;
);
}
search(search: string) {
this.filteredShopItems = this.allShopItems.filter(shopItem =>
shopItem.name.toLowerCase().includes(search.toLowerCase())
);
}
还尝试在 ngIf
上添加 filteredShopItems
以确保数据存在
<app-shop-items-list *ngIf="filteredShopItems" [shopItems]="filteredShopItems"></app-shop-items-list>