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});
})
}
}
添加回答
舉報