[英]every time a new object is pushed into array my loop in template repeats. how can I handle this in template?
I want to print a list of cars whenever a new object is added to my existing array. 我想在将新对象添加到现有阵列时打印汽车列表。 the loop repeats and i print from start again.
循环重复,我再次开始打印。 How can i avoid this ?
我怎么能避免这个?
I tried using async pipe and also track by
// in the service
getVehicles(){
obj = { data: [{name: 'car 1'},{name: 'car 2'}] }
return Observable.interval(2200).map(i=> obj.data.push({name: 'car 3'}));
}
// in the controller
vehicles: Observable<Array<any>>
ngOnInit() {
this.vehicles = this._vehicleService.getVehicles().obj.data;
}
// in template
<div *ngFor='let vehicle of vehicles | async'>
{{vehicle.name}}
</div>
expected car 1 car 2 car 3 car 3 预计车1车2车3车3
but it gives 但它给了
car 1 car 2 car 1 car 2 car 3 car 1 car 2 car 3 car 3 汽车1汽车2汽车1汽车2汽车3汽车1汽车2汽车3汽车3
I think this solution is very bad. 我认为这个解决方案非常糟糕。 I hope this is an exercise.
我希望这是一个练习。 The problem I think is this:
我认为这个问题是这样的:
vehicles: Observable<Array<any>>
getVehicles(){
this.vehicles=[];
obj=null;
obj = { data: [{name: 'car 1'},{name: 'car 2'}] }
return Observable.interval(2200).map(i=> obj.data.push({name: 'car 3'}));
}
// in the controller
ngOnInit() {
this.vehicles = this._vehicleService.getVehicles().obj.data;
}
Repeats in the view are probably caused by script errors (accessing some property of undefined) - isn't there anything in red in the console? 视图中的重复可能是由脚本错误(访问未定义的某些属性)引起的 - 控制台中是否有红色的东西? A lot of red?
很多红色?
Anyway: to add cars, you can 无论如何:要添加汽车,你可以
getVehicles() {
const obj = { data: [{name: 'car 1'},{name: 'car 2'}] };
return interval(2200).pipe(
map(() => {
const data = [...obj.data, { name: 'car 3' }];
return Object.assign(obj, { data });
});
);
}
To read them: 阅读它们:
ngOnInit() {
this.vehicles = this._vehicleService.getVehicles().pipe(
map(({ data }) => data)
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.