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

What is the process for combining and compressing an Angular 2 application?

I am currently trying to concatenate and minify an angular2 application. My approach so far involved concatenating all my *.js files (boot.js, application.js then all components) into one file and injecting it into my index.html. I also removed the <s ...

How to integrate a chips feature in Angular 4 using Typescript

Struggling to incorporate a chips component into my Angular web application, which comprises Typescript, HTML, and CSS files. After grappling with this for weeks without success, I have yet to find the right solution. To review my current code, you can a ...

Tips for preventing Angular from requiring an additional tag for a child component

Consider a scenario where I have a parent and child component in Angular 12. Their templates are structured as follows: Parent: <h1>This is the parent component</h1> <div class="container"> <div class="row"> ...

Utilizing Angular 2 for Displaying SVG Information

I am facing an issue with my angular application where I need to display product information in a SVG image obtained from a service in JSON format. Despite trying different methods, I have been unsuccessful in rendering the image on the HTML template. Att ...

Nested MD-list-item in Angular 2 Material

Trying to implement nested lists in a sidenav using Angular 2 with material design. Here is the initial code: <md-sidenav #sidenav class="sidenav" mode="over" opened> <md-nav-list> <md-card class="user-card"> ...

What is the best way to iterate through an array of arrays using a foreach loop to calculate the total number of specific properties?

For instance, if YieldCalcValues were to look something like this: [ [ 850, 500 ], [ 3, 6 ], [ 1200, 5000 ], [ 526170, 526170 ] ] I am looking to create a foreach loop that calculates the yield per for each product. How can I accomplish this correctly? l ...

No slides are available for display, resulting in the ngx-owl-carousel console message indicating that the carousel will not be re-rendered

I've been attempting to integrate ngx-owl-carousel-o into my Angular 11 application, but I keep encountering the following message in my console: There are no slides to show. As a result, the carousel will not be re-rendered. Unfortunately, nothing ...

The challenges of dealing with duplicate identifiers caused by nesting npm packages in TypeScript

I am facing an issue with my project structure where I have a node_modules folder at the root level and another one within a subfolder named functions. The directory layout looks like this, ├── functions │   ├── index.js │   ├── ...

Utilizing SCSS variables

Currently, I am in the process of developing an Angular 4 application using angular-cli and have encountered a minor issue. I am attempting to create a component that has the ability to dynamically load styling. The ComponentX component needs to utilize a ...

Angular 7 - ngForm and ngSubmit: Resubmitting outdated data

I have a form in Angular 7 set up like this: <form #payForm="ngForm" (ngSubmit)="onSubmit(payForm, $event)" method="POST" action="POST URL HERE"> <input type="hidden" name="requestParameter" [value]="stringToSend" /> <div class= ...

Can someone please explain how to bring in the Sidebar component?

click here for image description check out this image info An issue arises as the module '@components/Sidebar' or its type declarations cannot be located.ts(2307) Various attempts were made, including: import Sidebar from '@components/Sid ...

The journey of communication: uncovering the essence of @input between parent and

I'm diving into Angular and currently working on the @Input phase. Within my main app, there's a child component. Inside app.component.ts, I've declared a test variable that I wish to pass from app.component.ts to child.component.ts. // ap ...

Loading SVG templates dynamically in Angular can be done by utilizing a string

Is it possible to convert SVG content loaded from a server into a component template in Angular, with the ability to bind properties to it? For example, <tspan [attr.color]="textColor" ...>{{myText}}</tspan>. I have tried loading and ...

Steps for incorporating moment.js into an Angular 2 project

Having trouble importing moment.js into my angular2 application despite following various guides and solutions provided. Even though the package is present in my IDE (Visual Studio) and the moment.d.ts file is easily found, I keep encountering errors when ...

Fix the TypeScript issue encountered during a CDK upgrade process

After upgrading to version 2.0 of CDK and running npm install, I encountered an issue with the code line Name: 'application-name'. const nonplclAppNames = configs['nonplclAppNames'].split(','); let nonplclAppNamesMatchingState ...

Encountering a ng2-charts bug during Angular app testing

I encountered the TypeError: Cannot read property 'getBasePixel' of undefined error while running tests with a component that has a chart. Despite searching for solutions, I couldn't find any relevant information. I ensured the charts module ...

Is there a way to enable autofill functionality if an email already exists in the database or API within Angular 12?

In order to auto-fill all required input fields if the email already exists in the database, I am looking for a way to implement this feature using API in Angular. Any guidance or suggestions on how to achieve this would be greatly appreciated. ...

Consolidate multiple sorting functions into a single function to effectively sort by column

Can someone help me simplify my sorting function for array columns? Currently, I have multiple functions like the one below for each column: sort() { if (this.sortAsc == false) { this.tab.sort((a, b) => { return a.name.localeCompare( ...

Apologies, but your payment request was not successful. Please try using an alternative payment method or reach out to us for assistance. Find out more information about error code [OR

While trying to test Google Pay using a fake card, I encountered an error message stating: Your request failed. Use a different payment method, or contact us. Learn more [OR-CCSEH-21]. Below is the Angular code snippet that I am working with: paymentReques ...

Angular's capability for manipulating data asynchronously

I am relatively new to this, and I am facing difficulties in handling data manipulation in the frontend of an app that I'm currently developing. In my code, there are two functions named "getTipoEtapas()" and "getEtapasporTransfo" which utilize two s ...