What are the best ways to handle data using the .pipe() function?

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",

Answer №1

When tuning in to a stream, you employ the tap method which enables you to trigger side effects on the data such as saving it in session storage without impacting the stream

return this.svc.getBook().pipe(
  tap(book => { this.saveToSessionStorage("CachedBook", JSON.stringify(b)); })
)

Answer №2

Make sure to include a map operator in your code so that the return value is correctly added back to the stream:

return this.svc.getBook() // fetching data from remote API
  .pipe(
    map((b) => {
      this.saveToLocalStorage("CachedBook", JSON.stringify(b)); // ensure data is saved 
here
      return b;
    })
  );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting Angular 2 RC5: detectChanges function not functioning as expected

Currently, I am working on developing a login form component that has the following interface: <login-form onlogin="submit()"></login-form> Here is the testing code for this component: it("Ensuring credentials are passed correctly out of t ...

Error due to PlatformLocation's location dependency issue

My AppComponent relies on Location (from angular2/router) as a dependency. Within the AppComponent, I am using Location.path(). However, when running my Jasmine test, I encountered an error. Can you help me identify the issue with my Jasmine test and guide ...

Problem with Angular Slider

I'm in the process of creating a carousel component in Angular, but I'm facing an issue where the carousel is not appearing as it should. Below is the code for my carousel component. carousel.component.html: <div class="carousel"> ...

Setting up the TypeScript compiler locally in the package.json file

UPDATE #1: It appears that I have managed to come up with a functional configuration, but I am open to any suggestions for improvement. Feel free to check out the answer here: THE ORIGINAL INQUIRY: I am in the process of setting up my environment so that ...

typescript in conjunction with nested destructuring

ES6 has definitely made coding more efficient by reducing the number of lines, but relying solely on typescript for everything may not be the best approach. If I were to implement type checking for arguments that have been destructed multiple levels deep, ...

Is there a way to customize Material UI theme types and make adjustments to existing types using Typescript?

One way to customize the material ui theme is by extending its type and adding new properties, as shown here: For example, if we want to add an appDrawer property, it can be done like this: declare module '@material-ui/core/styles/createMuiTheme&apos ...

Angular 6 Subscription Issue: Problems with Variable Assignments

Currently, I am working on a map feature that utilizes the mapbox API and relies on the longitudinal and latitudinal coordinates obtained from a geocoder. There is a particular service in place that calls an endpoint with certain parameters. Upon subscrib ...

The scrolling feature is not working in NativeScript's ScrollView component

As I delve into using NativeScript with Angular to develop my debut mobile application, things have been going quite smoothly. However, a recent snag has halted my progress - the page refuses to scroll to reveal its entire content. To showcase this issue, ...

Definitions for images in the following format

I am currently utilizing typescript in conjunction with NextJs and next-images. Here is the code snippet: import css from "./style.sass"; import img from './logo.svg'; import Link from 'next/link'; export default () => <Link hre ...

Is error propagation from nested Promise to parent Promise not working properly in Node.js?

I'm currently working on a Node.js/TypeScript API with Express. Below is a snippet from my get method where I encountered an error in the format function. The error is caught by the promise, but it doesn't propagate to the parent promise after th ...

What is the method to cancel an Observable subscription without having a reference to the object of type "Subscription"?

If I were to subscribe to an Observable without an object of type "Subscription," how can I properly unsubscribe from it? For instance, if my code looks something like this: this.subscription = bla ... I know I can easily unsubscribe using the following ...

Angular 5: Display a blank URL with the source until the variables are resolved

In my template, if I have: <img src="/somepath/{{user?.UserGuid}}.png" /> When user is not yet resolved, the ?. prevents evaluating UserGuid, resulting in: <img src="/somepath/.png" /> Is there a way to prevent this without using *ngIf or c ...

Running Angular 2 build files with express.js: A step-by-step guide

Currently, I am trying to run index.html which is generated from an Angular2 app after using ng build. I attempted to use the following two lines of code individually, but unfortunately, neither of them worked for me: 1. app.use(express.static(path.resolv ...

Typescript - Defining string value interfaces

I have a property that can only be assigned one of four specific strings. Currently, I am using a simple | to define these options. However, I want to reuse these types in other parts of my code. How can I create an interface that includes just these 4 va ...

Design a Dynamic Navigation Bar with Angular Material to Enhance User Experience

I've put together a toolbar with Angular Material, but I'm facing responsiveness issues. How can I ensure the toolbar is responsive? Check out the code for the toolbar below: <md-toolbar color = "primary"> <button md-button class=" ...

Encountering a 403 status code from the Spotify Web API while attempting to retrieve data using an OAuth 2.0 Token

I'm currently experimenting with the Spotify Web API and attempting to retrieve my most played songs. To obtain an access token for making requests, I am utilizing the client credentials OAuth flow. While I have successfully obtained the access token, ...

pressing the switch will adjust the size of the container

I am looking to implement a feature where clicking on an icon will resize a div to full screen in the browser. Below is the HTML code I have set up for this functionality, and I am open to suggestions on how to achieve this. <div> <a (click)= ...

Enhancing TypeScript with Generic Proxyify Functionality

I'm attempting to enclose a basic interface provided through a type generic in order to alter the return value of each function within the interface. For instance: interface IBaseInterface { test(a?: boolean, b?: number): Promise<boolean>; ...

What's the best way to replicate a specific effect across multiple fields using just a single eye button?

Hey everyone, I've been experimenting with creating an eye button effect. I was able to implement one with the following code: const [password, setPassword] = useState('') const [show, setShow] = useState(false) <RecoveryGroup> ...

Creating multiple dynamic dashboards using Angular 4 after user authentication

Is there a way to display a specific dashboard based on the user logged in, using Angular 4? For example: when USER1 logs in, I want dashboard 1 to be visible while hiding the others. Any help would be greatly appreciated... ...