我有一个带有events
服务的Angular 2应用,其中有delete
方法:
let EVENTS: TimelineEvent[] = [
{
event: 'foo',
timestamp: 1512205360,
},
{
event: 'bar',
timestamp: 1511208360,
}
];
@Injectable()
export class EventsService {
getEvents(): Promise<TimelineEvent[]> {
return Promise.resolve(EVENTS);
}
deleteEvent(deletedEvent) {
EVENTS = EVENTS.filter((event) => event.timestamp != deletedEvent.timestamp);
}
}
我的主要组件显示这些事件,并使用onClick
处理程序调用服务的deleteEvent
方法:
@Component({
selector: 'my-app',
providers: [EventsService],
template: `
<div>
<event *ngFor="let timelineEvent of events" [timelineEvent]="timelineEvent" [deleteEvent]="deleteEvent"></event>
</div>
`,
})
export class App implements OnInit {
constructor(private eventsService: EventsService) {
}
events
getEvents(): void {
this.eventsService.getEvents().then(events => this.events = events);
}
deleteEvent(event): void {
this.eventsService.deleteEvent(event);
}
ngOnInit(): void {
this.getEvents();
}
}
我可以通过console.logging
EVENTS
数组看到这是正确更新的。但显示不会更新。我哪里错了?
答案 0 :(得分:1)
您可以删除服务中的事件,而不是组件中的事件。组件中的事件列表仍未更新。
解决问题的方法:
1 - 使服务的deleteEvent方法返回promise:
deleteEvent(deletedEvent) {
EVENTS = EVENTS.filter((event) => event.timestamp !== deletedEvent.timestamp);
return Promise.resolve("Successfully deleted");
}
2 - 在您的组件中,重新加载有关删除操作成功的事件:
deleteEvent = (event) => {
this.eventsService.deleteEvent(event).then(res => this.getEvents());
}