I'm trying to pipe valueChanges from a select to fire off the appropriate API request and show a spinner while the response hasn't been received. On top of that I'm trying to use publish() and refCount() so that I can use that observable with the async pipe in multiple places in my template.
my-component.ts
ngOnInit() {
this.results$ = this.selectControl.valueChanges.pipe(
startWith('hard'),
switchMap((evalStrategy: 'hard' | 'soft') => this.apiService.getResults(evalStrategy)),
publish(),
refCount()
);
}
my-component.html
<mat-progress-spinner *ngIf="!(results$ | async)"></mat-progress-spinner>
<div *ngIf="results$ | async">
<p>Name {{(results$ | async).name}}</p>
<small>{{(results$ | async).description}}
</div>
Ideally, I'd expect this code to work and only fire off just 1 request to the server.
But I end up getting Cannot read property 'name' of null :(
If I make the following change to my-component.html
<mat-progress-spinner *ngIf="!(results$ | async)"></mat-progress-spinner>
<div *ngIf="(results$ | async) as results">
<p>Name {{(results).name}}</p>
<small>{{(results).description}}
</div>
Then it works fine and the only fire's off 1 request to the server. But when you change the select option, results$ | async no longer evaluates to null until the new value is available. Instead, it sticks with the old value and then all of a sudden replaces it with the updated one.
results$ | asyncshould be changed tonulluntil the new value is available? - Chybie(results)?.name? - user4676340