2017-05-10 51 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()時,確切的問題是什麼?你的代碼應該返回值。您可以創建角度服務來獲取和設置值。我想我真的明白你的問題。 –