Looking to optimize an Angular component Typescript function that returns an Observable<book[]>. The logic involves:
If (data exists in sessionStorage) Then
return it
Else
get it from remote API
save it in sessionStorage
return it
End If
Here is how it's currently implemented:
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() // fetching from remote API
.pipe((b) =>
{
this.setIntoSessStorage("CachedBook", JSON.stringify(b));
return b;
});
}
There are no errors, but the issue arises when the data b
returned is not being saved. It seems like there might be something missing within the .pipe()
function. However, the setIntoSessStorage()
function works perfectly fine outside of this one.
Current package versions used:
"@angular/cli": "~14.2",
"rxjs": "~7.4.0",
"typescript": "~4.7.4",