I have an API call that may return some data or may return something falsey if no data exists. If there is data, I want to tap out of the stream and do some side effects, but if falsey, I want no side effects to happen but still display my template code.
I am using an async pipe to get that data in the template, but if the data is falsey, it will not display.
I have seen the technique to wrap the ngIf with an object so it evaluates to truthy, but it doesn't seem the correct solution for my code.
My template:
<form *ngIf="loadedData$ | async">
...
</form>
My class:
loadedData$: Observable<boolean>;
ngOnInit(): void {
this.loadedData$ = this.getCurrentBranding().pipe(
tap(branding => {
if (branding) {
// Do side effects
}
}),
// current hack to make the template show
map(() => true)
);
}
private getCurrentBranding(): Observable<Branding> {
// API call, may return an object, or null
}
pipeis the correct place to resolve side effects of the observable that is not a hack, it's just a legit approach to it. Or you could do the wrapping inside the map operator. You can use something like :map((result) => ({isSuccess : !!result, result}))mapTo(true)to save a few characters and show off your rxjs knowledge ;)