2017-02-25 69 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