I'm facing an issue with my Angular page where the UI is not updating when the observable parameter from a service changes.
I've experimented with storing the observable result in a flat value and toggling a boolean to update the UI, but none of these approaches have worked.
Upon logging the observable, I can verify that it is updating correctly. Interestingly, navigating back to the page displays the updated value.
All other conditional UI updates work as expected, except for the one below (
*ngIf="(entries$ | async), else loading"
) which seems to be causing the problem.
component.ts
export class EncyclopediaHomeComponent implements OnInit {
entries$: Observable<EncyclopediaEntry[]>;
categories$: Observable<string[]>;
entry$: Observable<EncyclopediaEntry>;
entry: EncyclopediaEntry;
isEditing: boolean;
constructor(private route: ActivatedRoute, private encyService: EncyclopediaService) {
this.entries$ = encyService.entries$;
this.categories$ = encyService.categories$;
this.entries$.subscribe(es => {
console.log(es);
});
route.url.subscribe(url => this.isEditing = url.some(x => x.path == 'edit'));
this.entry$ = route.params.pipe(
switchMap(pars => pars.id ? encyService.getEntry(pars.id) : of(null)),
);
this.entry$.subscribe(entry => this.entry = entry);
}
ngOnInit(): void {
}
updateEntry(entry: EncyclopediaEntry) {
this.encyService.updateEntry(entry.id, entry);
}
}
component.html
<div class="encyclopedia-container">
<ng-container *ngIf="(entries$ | async), else loading">
<app-enc-list [entries]="entries$ | async"
[selectedId]="entry ? entry.id : null"></app-enc-list>
<ng-container *ngIf="entry">
<app-enc-info *ngIf="!isEditing, else editTemplate"
[entry]="entry$ | async"></app-enc-info>
<ng-template #editTemplate>
<app-enc-edit [entry]="entry$ | async" [categories]="categories$ | async"
(save)="updateEntry($event)"></app-enc-edit>
</ng-template>
</ng-container>
</ng-container>
<ng-template #loading>
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
<br>
<p>Loading Encyclopedia...</p>
</ng-template>
</div>
edit: service.ts
export class EncyclopediaService {
entriesSubject = new ReplaySubject<EncyclopediaEntry[]>();
entries$ = this.entriesSubject.asObservable();
private _entries: EncyclopediaEntry[];
constructor(private file: FileService) {
file.readFromFile(this.projectName+'Encyclopedia').subscribe((es: string) => {
this._entries = JSON.parse(es);
this.entriesSubject.next(this._entries);
this.entries$.subscribe(es => this.file.writeToFile(this.projectName+'Encyclopedia', JSON.stringify(es)));
});
}
.
.
.
}