2017-02-25 70 views
0

我做一個簡單的項目空數組:角2:在組分HTML

有2個輸入滑塊和按鈕「計算」,當按下按鈕時,計算完成和印刷到表中。

我有一個小問題,當我按下按鈕時,表組件顯示答案數組是空的,但如果我從構造函數將它打印到控制檯,一切都會顯示出來。

有人可以幫忙嗎? 我想做一個*ngFor並稍後循環遍歷元素。

服務:

@Injectable() 
export class DataService { 

    loanArray: Payment[] = []; 

    setCalculatedPayments(loanSum: number, loanTime:number) { 
    this.loanArray = new PaymentsCalculated(loanSum, loanTime).calculateLoanDetails(); 
    } 

    getCalculatedPayments() { 
    return this.loanArray; 
    } 
} 

貸款部分:

export class LoanTablesComponent implements OnInit { 

    loanArray: Payment[] = []; // is it always empty? 

    constructor(private DataService: DataService) { 
    this.loanArray = this.DataService.getCalculatedPayments(); 
    // here it prints the loanArray as required 
    // but if I print out in the .html, it is always zero 
    } 

    ngOnInit() { 
    } 

} 

計算部件:

export class CalculatorComponent implements OnInit { 

    loanSum: number; 
    loanTime: number; 

    constructor(private DataService: DataService) { 
    setTimeout(() => this.loanSum = 500); 
    setTimeout(() => this.loanTime = 1); 
    // for input sliders 
    } 

    ngOnInit() { 
    } 

    calculatePayments(): void{ 
    this.DataService.setCalculatedPayments(this.loanSum, this.loanTime); 
    } 

} 

感謝您的幫助,剛開始學習和尋求建議(:

+0

'CalculatorComponent'和'LoanTablesComponent'之間的關係是什麼? – AngularChef

+0

計算器顯示用於計算的輸入的輸入UI,當按下按鈕時它將數據提供給數據服務,貸款表輸出表,從數據服務中取數據 –

+0

好的。但我的意思是他們如何在組件樹**中關聯**? (例如,是否是另一個的孩子?)看起來你有一個時間問題:一旦'LoanTablesComponent'實例化,你嘗試讀取數據,但直到你調用setCalculatedPayments()'它才被設置。如果'loanArray'包含非原始值,我認爲變更檢測不能用於您的設置。也許嘗試用[get property](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get)替換'LoanTablesComponent'中的'loanArray'? – AngularChef

回答

0

在結束 我剛剛通過@Output和@Input傳遞了參數,學習服務是針對其他thigs的:D