The component seen below would display a list of events in the template upon initialization ( ngOnInit()
). However, when the addEvent()
is invoked, the view will not be updated. Why is this the case?
How can I make the view to be updated whenever I publish new data to a data store that's used to populate the observable property ( events: Observable<Event[]>
)?
@Component({
template:
<ul>
<li *ngFor="let event of events | async"
{{ event.title }}
</li>
</ul>
<button (click)="addEvent()">Add event</button>
})
export class EventCenterListComponent implements OnInit {
events: Observable<Event[]>;
constructor(
private eventsService: EventsService,
) {}
ngOnInit() {
this.events = return this.eventsService.getEvents();
}
addEvent() {
this.eventsService.createEvent('New event'); <--this would add one event to the data source
this.events = this.eventsService.getEvents(); <-- that reassignment would not be seen in the template
}
}
I've seen that many tutorials, including Angulat's official tutorial convert the Observable into a plain array and then push
new values into the array, eg:
heroes: Hero[];
addHero(name: string) {
this.heroService.create(name)
.subscribe(
hero => this.heroes.push(hero), <-- that would work
error => this.errorMessage = <any>error);
}
But is the above really necessary? Cannot I operate directly on observables and have the view updated?
Yeah, better not to subscribe in the component.
Here's one idea. The events service keeps a private array of events, and fires a subject every time it changes. The component can use the async pipe so that its view is updated whenever that subject fires.
@Injectable()
export class EventsService {
private events: Event[] = [];
private eventsSubject = new Subject<Event[]>();
private _events$ = this.eventsSubject.asObservable();
createEvent(title: string) {
const newEvent: Event = {title};
this.events = [...this.events, newEvent];
this.eventsSubject.next(this.events);
}
getEvents$() {
return this._events$;
}
}
@Component({
template: `
<ul>
<li *ngFor="let event of events | async">{{ event.title }}</li>
</ul>
<button (click)="addEvent()">Add event</button>`
})
export class EventCenterListComponent {
events: Observable<Event[]>;
constructor(private eventsService: EventsService) {
this.events = eventsService.getEvents$();
}
addEvent() {
this.eventsService.createEvent('New event');
}
}
UPDATE
New idea from a closer reading of your question. Assuming EventService works like this:
createEvent(title: string): Observable<void> // post one new event to server
getEvents(): Observable<Event[]> // get list of events from server
...And you simply want to refetch the list of the events after posting a new one, then implement EventCenterListComponent like this:
export class EventCenterListComponent {
events: Observable<Event[]>;
private newEventSubject = new Subject<string>();
constructor(eventsService: EventsService) {
const eventWasCreated$ = this.newEventSubject.mergeMap(title =>
eventsService.createEvent(title));
const shouldRefresh$ = eventWasCreated$.startWith(undefined);
this.events = shouldRefresh$.switchMap(() =>
eventsService.getEvents());
// optional, if you are going to subscribe to `events` in more
// than one place:
this.events = this.events.share();
}
addEvent() {
this.newEventSubject.next('New event');
}
}
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.