我有一个继承自父组件的子组件 .
父组件正在执行api请求并将数据传递给子组件 .
父组件:
export class ChartComponent implements OnInit {
@Input()
protected exercisesData: any[];
@Input()
protected weightData: any[];
/**
*
*/
constructor(public dataService: DataService) {
}
ngOnInit(): void {
this.dataService.setEndpoint('/api/dashboard/get');
this.get();
}
private get() {
this.dataService
.Get()
.subscribe(data => {
this.exercisesData = Object.assign({}, data);
this.weightData = Object.assign({}, data);
console.log(this.exercisesData);
console.log(this.weightData);
}, (error) => {
console.log(error);
});
}
}
子组件:
export class ExercisesProgressChartComponent extends ChartComponent{
private filterableData: any[];
private dropDownSelectedValue: string;
ngOnInit(): void {
this.dropDownSelectedValue = "0";
this.filterableData = Object.assign({}, this.exercisesData);
}
private onDropDownChange(dropDownSelectedValue) {
if(dropDownSelectedValue == "0"){
this.filterableData = Object.assign({}, this.exercisesData);
}
else{
this.filterableData = Object.assign({}, this.exercisesData);
this.filterableData["exercisesProgress"] = this.filterableData["exercisesProgress"].filter(x=>x.id == dropDownSelectedValue);
}
}
}
子组件模板:
<div *ngIf="exercisesData" class="dashboard">
<div class="form-group">
<select class="form-control" [(ngModel)]="dropDownSelectedValue" (ngModelChange)="onDropDownChange($event)" sele>
<option [value]="0">All Exercises</option>
<option *ngFor="let x of exercisesData.exercisesProgress" [value]="x.id">{{x.name}}</option>
</select>
<small id="exerciseNameHelp" class="form-text text-muted">Please select exercise for filtering</small>
</div>
{{exercisesData.exercisesProgress | json}}
{{filterableData.exercisesProgress | json}}
<ngx-charts-line-chart
[scheme]="{domain: ['#5AA454', '#A10A28', '#C7B42C', '#AAAAAA']}"
[results]="filterableData.exercisesProgress"
[gradient]="false"
[xAxis]="true"
[yAxis]="true"
[legend]="true"
[showXAxisLabel]="true"
[showYAxisLabel]="true"
[xAxisLabel]="Date"
[yAxisLabel]="Weight"
[autoScale]="true"
(select)="onSelect($event)">
</ngx-charts-line-chart>
</div>
当组件本身中的值未定义时,如何确保我可以分配给this.filterableData?在模板中,我可以使用* ngIf,但是如何在组件级别执行此操作?由于* ngIf检入模板,显然也没有分配 dropDownSelectedValue .
2 回答
当
subscribe()
返回数据时,您有机会在那里做一些事情 . 我看到两个选择:在
ChartComponent
中仅保留get()
作为Observable并在ChildComponent
中订阅它 . 因此,在subscribe()
中,您可以将结果重新分配给filterableData
.保持
get()
它是怎么回事并在Component
中调用一个方法进行转换,但在Component
中它是空的,你在ChildComponent
中覆盖它来做你想要的我没有继承就解决了它,因为继承它仍然会做两个请求 .
我在父组件中声明了变量:
然后在父组件的模板中我传递了dashboardData(它是数组,但testProgress和testSecondProgress是嵌套数组,我将每个组件传递给相应的子组件):
然后在我要传递数据的子组件中,我已经声明了一个变量:
对于新来者,您可以看到链接行为:
同样重要的是,要能够在子组件中填充可变数据,在使用父模板中的* ngIf进行渲染之前不要忘记等待它:
由于api请求是异步的,如果你不等待,它将尝试在数据恢复之前呈现模板,这会引发错误 data is undefined .