3 回答
TA贡献1998条经验 获得超6个赞
从您的 html 代码中,我认为您需要一个对象数组。例如 :
array = [
{key: 'key1', title: 'title 1', price: 10, },
{key: 'key2', title: 'title 2', price: 10, },
{key: 'key3', title: 'title 3', price: 10, }
]
如果我的假设是正确的,那么这里有几个问题。
数组构造不行。
您的数组变量是本地的。将其设为公共变量,否则无法从 html 访问它。
在 html 中,您正在尝试迭代数组,每次迭代时,数据将分配在您的局部变量中
'p'
(如您所用*ngFor="let p of array"
)
所以,把你的代码改成这样
import { ProductsService } from './../../products.service';
import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, AngularFireAction, DatabaseSnapshot } from 'angularfire2/database';
@Component({
selector: 'app-admin-products',
templateUrl: './admin-products.component.html',
styleUrls: ['./admin-products.component.css']
})
export class AdminProductsComponent{
array: any = [];
constructor(
private products:ProductsService,
private db : AngularFireDatabase
) {
products.getAll().on('child_added',function(c){
let data = c.val();
let key = c.key;
let price = data.price;
let title = data.title;
this.array.push({"key":key, "title":title, "price":price });
console.log('array of data', this.array);
})
}
}
并将您的 html 更改为此,
<table class="table">
<thead>
<th>Title</th>
<th>Price</th>
<th></th>
</thead>
<tbody *ngFor="let p of array">
<td>{{p.title}}</td>
<td>{{p.price}}</td>
<td ><a [routerLink]="['/admin/products',p.key]">Edit</a></td>
</tbody>
</table>
TA贡献1155条经验 获得超0个赞
像这样尝试:
有循环
tr
而不是td
将 {{array.title}} 改为 {{p.title}}
让
array
全球
.html
<tbody>
<tr *ngFor="let p of array">
<td>{{p.title}}</td>
<td>{{p.price}}</td>
<td ><a [routerLink]="['/admin/products',p.key]">Edit</a></td>
</tr>
</tbody>
.ts
export class AdminProductsComponent{
array:any[] = [];
products.getAll().on('child_added',function(c){
let data = c.val();
let key = c.key;
let price = data.price;
let title = data.title;
this.array=[];
this.array.push({"key":key});
this.array.push({"title":title});
this.array.push({"price":price});
console.log('array of data',this.array);
})
}
TA贡献1813条经验 获得超2个赞
在您的组件中定义一个数组属性并将对象传递给它。对 on 回调使用 Arrow 函数,这样你的 this 上下文就是组件。
import { ProductsService } from './../../products.service';
import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, AngularFireAction, DatabaseSnapshot } from 'angularfire2/database';
@Component({
selector: 'app-admin-products',
templateUrl: './admin-products.component.html',
styleUrls: ['./admin-products.component.css']
})
export class AdminProductsComponent{
// Define property here
public array = [],
constructor(
private products:ProductsService,
private db : AngularFireDatabase
) {
products.getAll().on('child_added',(c) => {
let data = c.val();
let key = c.key;
let price = data.price;
let title = data.title;
this.array.push({key, title, price});
})
}
}
添加回答
举报