I have a Angular component Typescript function to return an Observable<book[]>. Logic is
If (data exists in sessionStorage) Then
return it
Else
get it from remote API
save it in sessionStorage
return it
End If
Implementated as:
import { Observable, of, pipe } from 'rxjs';
getData(): Observable<book[]>
{
var CachedBook = (this.getFromSessStorage("CachedBook") != "") ?
JSON.parse(this.getFromSessStorage("CachedBook")) : [];
if (CachedBook.length > 0)
return of(CachedBook);
else
return this.svc.getBook() // remote API
.pipe((b) =>
{
this.setIntoSessStorage("CachedBook", JSON.stringify(b)); // <-- never save data from
here
return b;
});
}
It produces no error, but when data b
returned it's not saved. There must be something I've not done right inside the .pipe()
. Function setIntoSessStorage()
is working fine outside of this function.
Package versions:
"@angular/cli": "~14.2",
"rxjs": "~7.4.0",
"typescript": "~4.7.4",
To listen to a stream you use tap, it allows you to cause side effects with the data like storing it in session storage without affecting the stream
return this.svc.getBook().pipe(
tap(b => { this.setIntoSessStorage("CachedBook", JSON.stringify(b)); })
)