2017-05-10 26 views
0

我制作了一个通过@Input接收数据的视图组件。 如何获得值的总和?我尝试在构造函数和函数中,但似乎没有正确工作。获取Typescript类中的值的总和

这里是我的示例代码 接口和类

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; 
 
    } 
 
}

我的角度成分

@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']; 
 
     }); 
 
    }

+1

定义它“似乎并不正确。” – Daryl

+0

您的Angular组件与您的图表数据有什么关系? –

回答

1

你需要在课堂上(myChartData)全局变量。然后在构造函数中,您需要填充它,然后从getTotal()函数中返回全局值。

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"]; 
    } 
    } 
+0

这很混乱。你有一个实现'IChartData'的类,然后它还拥有'IChartData'的实例? –

+0

当您尝试getTotal()时,确切的问题是什么?你的代码应该返回值。您可以创建角度服务来获取和设置值。我想我真的明白你的问题。 –