从Angular服务中删除对象

时间:2017-09-21 22:14:25

标签: javascript angular angular-services

我在Angular 2应用中有一项服务,events.service.ts

const EVENTS = {
  1512205360: {
    event: 'foo'
  },
  1511208360: {
    event: 'bar'
  }
}

@Injectable()
export class EventsService {
  getEvents() {
    return EVENTS;
  }
  deleteEvent(timestamp) {
    delete EVENTS[timestamp];
  }
}

我有一个home组件,在getEvents挂钩中调用此服务的ngOnInit方法:

getEvents(): void {
    this.events = this.eventsService.getEvents();
    this.eventKeys = Object.keys(this.events);
}

ngOnInit(): void {
    this.getEvents();
}

home组件的模板只是循环遍历事件并将其打印出来,每个事件旁边都有一个delete图标:

<event *ngFor="let eventKey of eventKeys" [timestamp]="eventKey" [title]="events[eventKey].event"></event>

这是event组件:

@Component({
  selector: 'event',
  templateUrl: './event.component.html',
  providers: [EventsService]
})
export class EventComponent {
  @Input() timestamp: string;
  @Input() title: string;
  constructor(private eventsService: EventsService) { }

  deleteEvent(timestamp) {
    this.eventsService.deleteEvent(timestamp);
  }
}

点击delete图标会调用deleteEvent服务中的events方法。我的问题是,当我点击delete图标时,虽然我可以看到该事件已被删除(console.logging EVENTS对象),但home组件不是&# 39; t更新并产生此错误:

  

无法阅读财产&#39;事件&#39;未定义的

1 个答案:

答案 0 :(得分:2)

重点是HomeComponent.eventKeys数组未与HomeComponent.events对象关联,EVENTS对象与HomeComponent.eventKeys关联。您可以通过HomeComponentObject.keys()开头设置HomeComponent.events数组一次。 EVENTS(和HomeComponent.eventKeys)的所有操作都不会影响ngFor数组。因此,events会继续跟踪初始密钥数组并炸掉未发现的HomeComponent.eventKeys项。

有许多可能的解决方案,但主要想法是将EVENTSHomeComponent同步。例如,可以通过将删除方法从EventComponent传递到eventKeys并在删除后重新计算// HomeComponent deleteEvent(timestamp) { this.eventsService.deleteEvent(timestamp); this.getEvents(); } 数组来完成此操作:

char

<强>更新

刚刚为这种情况创建了一个plunk演示,享受:https://plnkr.co/edit/ogfmEY?p=preview