【发布时间】:2021-12-23 10:02:26
【问题描述】:
我有两个组件,一个父组件和一个子组件。在父组件中,我有一个空数组:
publicCrowsOnPerchValues: number[] = [];
我使用这个数组在使用chart.js 的图表上显示数据。我正在使用 Firebase 的 RTDB 来存储和检索数据。以下是上述数组在父组件中的填充方式:
getCrowOnPerchDataChildren() {
//get a snapshot of the child added
this.$childCrowOnPerchSub = this.crowboxService
.getCrowOnPerchData()
.stateChanges();
this.$childCrowOnPerchSub
.subscribe(action => {
//set the showUserId to false as the user has already set up the crowbox
this.showUserId = false;
//get the index of the key from the date array
let indexOfKey = this.crowsOnPerchDate.indexOf(action.key);
//if the index is -1, then the date does not currently exist
//this means that it is a new date, so we push it onto the array
//since it is a new date, we also push on the value onto the value
//array
if (indexOfKey == -1) {
this.crowsOnPerchDate.push(action.key);
this.crownsOnPerchValues.push(action.payload.val().value);
} else {
//if it does exist, then we don't need to add the new date
//simply replace the existing data value with the new data value
//for the same date
this.crownsOnPerchValues[indexOfKey] = action.payload.val().value;
}
//reset the bar charts data as well as labels
this.crowOnPerchChartLabels = this.crowsOnPerchDate;
this.crowOnPerchChartData = [
{ data: this.crownsOnPerchValues, label: "Number Of Crows That Landed On The Perch" }
];
});
}
在上述函数中,我实质上是在用户将数据添加到 Firebase RTDB 时填充数组。它通过订阅 observable 起作用。
现在,我想将此数组传递给我的子组件。
在子组件中,我设置了一个Input() 变量,如下所示:
@Input() crowsOnPerch!:number[];
然后,在 parent.component.html 中,我像这样传递数组:
<app-child [crowsOnPerch]="crownsOnPerchValues"></app-child>
这可行,但我收到的是空数组。我怎样才能在更新时不断收到阵列?我应该改用共享服务吗?
【问题讨论】:
-
只是猜测:可能是异步管道
标签: angular angular-components