我创建了一个通过@Input接收数据的视图组件。 如何获得价值总和?我试过构造函数和函数,但似乎没有正常工作。
这是我的示例代码 接口和类
interface IChartData {
date: string;
dogs: number;
cats: number;
total: number;
}
class ChartData implements IChartData {
constructor(public date: string, public dogs: number, public cats: number, public total: number=0 ){
this.total = this.dogs + this.cats;
}
getTotal() {
return this.dogs + this.cats;
}
}
My Angular组件
@Component({
selector: 'animal-chart',
templateUrl: 'animal.component.html',
providers: [ ],
})
export classAnimalChartComponent extends Translation implements OnInit {
private _data = new BehaviorSubject<Object>({});
values: MaintenanceChartData[] = [];
constructor(public locale: LocaleService,
public localization: TranslationService,) {
super(localization);
}
@Input()
set data(value) {
// set the latest value for _data BehaviorSubject
this._data.next(value);
};
get data() {
// get the latest value from _data BehaviorSubject
return this._data.getValue();
}
ngOnInit() {
this._data
.subscribe(x => {
this.values = x['result'];
});
}
答案 0 :(得分:1)
您需要在类(myChartData)中使用全局变量。然后在构造函数中,您需要填充它,然后在getTotal()函数中返回global的值。
interface IChartData {
date: string;
dogs: number;
cats: number;
total: number;
}
class ChartData implements IChartData {
myChartData: IChartData;
constructor(public date: string, public dogs: number, public cats: number, public total: number=0 ){
// this.myChartData["date"] = date;
// this.myChartData["dogs"] = dogs;
// this.myChartData["cats"] = cats;
// this.myChartData["total"] = total;
this.myChartData = {
date: date,
dogs: dogs,
cats: cats,
total: total
}
}
getTotal() {
this.myChartData["total"] = this.myChartData["dogs"] + this.myChartData["cats"];
return this.myChartData["total"];
}
}