【发布时间】:2017-06-21 18:14:06
【问题描述】:
我对 Angular 2 很陌生,我想通过 @Input() 将在父组件中创建的数组传输给它的子组件。
在父级中,我创建了数组,从服务中添加数据,并将其显示在控制台中(控制台输出 1)。然后在子组件中,我使用 ngOnChanges 再次在控制台中显示它(控制台输出 2)。如下图所示,数组的长度从 12 变为 0。我想这是因为数组在传递给子时变成了对象?
我该如何解决这个问题?
父母
import { Component, OnInit } from '@angular/core';
import { Module, MapMarkerData } from './coreclasses';
import { TimelineService } from './input.service';
@Component({
selector: 'my-app',
templateUrl: 'app/app.component.html',
providers: [TimelineService]
})
export class AppComponent implements OnInit {
modules: Module[];
mapMarkerData: any;
constructor(private timelineService: TimelineService) {
this.mapMarkerData = new Array<MapMarkerData>();
}
getModules(): void {
this.timelineService.getModules().then(modules => {this.modules = modules; this.setMapModuleData(this.modules);});
}
setMapModuleData(modules: Array<any>): void {
for (let module of modules) {
if (module.className) {
var id = module.id;
var className = module.className;
let contents: Object = {id: id, className: className};
this.mapMarkerData.push(contents);
}
}
console.log(this.mapMarkerData); // CONSOLE OUTPUT 1
console.log(this.mapMarkerData.length);
}
}
孩子
import { Component, Input, OnInit, OnChanges, SimpleChanges } from '@angular/core';
import { MapMarkerData } from './coreclasses';
@Component({
selector: 'timeline-map',
templateUrl: 'app/timeline.map.component.html'
})
export class TimelineMapComponent implements OnChanges {
@Input()
mapMarkerData: any;
ngOnChanges(changes: any) {
console.log(this.mapMarkerData); // CONSOLE OUTPUT 2
console.log(this.mapMarkerData.length);
}
}
父模板
...
<div id="map" class="mapLarge">
<timeline-map [mapMarkerData] = "mapMarkerData"></timeline-map>
</div>
...
控制台输出 1 数组[12]:[对象,对象,...]
控制台输出 2 数组[0]:[对象,对象,...]
【问题讨论】:
-
数组在传递给孩子时不会改变。我怀疑
Console Output 2是在Console Output 1之前打印的。不是这样吗? -
更改由
changes.mapMarkerData.currentValue访问
标签: arrays angular ngonchanges