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
but it gives
car 1 car 2 car 1 car 2 car 3 car 1 car 2 car 3 car 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)
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.