【发布时间】:2017-01-12 15:24:34
【问题描述】:
我正在使用DashboardComponent 从我的DashboardService 获取数据。然后这个组件将我的对象数组传递给我的表单组件。
(帖子底部的Plunkr链接)
DashboardComponent.ts
private bottleArray: Bottle[] = [];
ngOnInit() {
// Get bottle types from service to the form needing them
this.dashboardService.getBottleTypesAndNames()
.subscribe(bottlesData => {
bottlesData.forEach(bottle => {
// Convert to Bottle type
let bottleObject: Bottle = new Bottle(bottle.bottleTypeId, bottle.bottleName);
this.bottleArray.push(bottleObject);
});
});
}
DashboardComponent.html
<ct-create-order-form [bottleArray]="bottleArray"> </ct-create-order-form>
我这样做是为了让链接到我的Dashboard 的表单组件不会调用我的服务。
我正在尝试clone我的@Input,以便我从表单更新的数据未链接到我的父组件(仪表板),但我似乎无法做到这一点......见下面的代码:
CreateOrderFormComponent.ts
export class CreateOrderFormComponent implements OnChanges {
@Input() private bottleArray: Bottle[];
constructor() { }
private clonedBottleArray: BottleCommand[];
ngOnChanges(changes) {
if (changes.bottleArray) {
let test: BottleCommand[] = changes.bottleArray.currentValue;
// Cloning
console.log(test); // Array of 6 Bottles
this.clonedBottleArray = [...test];
console.log(this.clonedBottleArray); // Empty Array
this.clonedBottleArray = Array.from(test);
console.log(this.clonedBottleArray); // Empty Array
this.clonedBottleArray = test.slice();
console.log(this.clonedBottleArray); // Empty Array
this.clonedBottleArray = test;
console.log(this.clonedBottleArray); // Array of 6 bottles
}
}
有什么方法可以实现我正在做的事情吗?我不明白为什么我在获取数据时无法克隆我的输入?
从 AngularConnect 制作的这个 Youtube 视频中,他正在做同样的事情,只是他正在操作一个对象,而我正在操作一个对象数组。
https://youtu.be/-nsedZwvl9U?t=12m22s
编辑:创建 Plunkr 后,这似乎在那里正常工作。
https://plnkr.co/edit/js1vl0fcgOKtQNqXsWTL?p=preview
EDIT 2:在我的DashboardComponent 的ngOnInit(),如果我模拟数据,它会正确克隆到我的子组件中。
【问题讨论】:
标签: arrays angular ecmascript-6 clone ngonchanges