The Angular service not only stores data but also handles HTTP requests internally

Instead of returning an observable to the requesting components and managing the data, I am considering using Angular services to handle HTTP requests autonomously. The goal is to have components retrieve data directly from the service where it is stored.

The idea is that if the data is already loaded and up to date (loaded within the past minute), it can be quickly returned to the requesting component. If not, the service will load and store the data before providing it to the component.

Angular tutorials typically show services returning observables that components must subscribe to and manage the data themselves.

Does my approach seem logical?

In my current prototype, I have multiple components needing the same data, so loading it multiple times is inefficient. I am also trying to avoid using Redux or similar frameworks.

Can anyone provide an example of a service that handles HTTP requests internally and manages the data?

Thank you in advance.

Answer №1

Utilizing behavior subjects can greatly benefit your data management. They store your data and allow you to easily update it.


data = new BehaviorSubject<any>(null);

fetchData() {
  this.http.get(...).subscribe(res => this.data.next(res));
}

// In your component

this.service.data.asObservable().subscribe(console.log);

While this approach is straightforward, I recommend exploring Akita JS, a library designed to simplify this process. Akita JS offers a more user-friendly alternative to Redux, with minimal complexity.

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

Determine the type of input and output based on another argument

When working with a function that takes an object of either TypeA or TypeB, the first parameter is used to specify the type of the object and the returned type depends on this first parameter. The issue arises in TypeScript where the type of the object is ...

Error: It is not possible to assign a value to the Request property of the Object since it only has a getter method

Encountering issues while attempting to deploy my Typescript Next.js application on Vercel. The build process fails despite functioning correctly and building without errors locally. Uncertain about the root cause of the error or how to resolve it. The f ...

I am experiencing an issue with my Angular application where it appears blank on gh-pages and is unable to load JavaScript from Travis

After uploading an Angular app with Travis on Github pages using the gh-pages branch, I'm encountering a frustrating issue. The page is blank and there are several error messages in the console: Failed to load resource: https://hdz.github.io/runtime.j ...

Modal component not displaying properly in ng-bootstrap framework

I'm having trouble getting a modal and its background to display when activated. The elements are being created and destroyed correctly in the developer tools, but they are not visible on the page. I'm trying to replicate the example from this li ...

Properly passing props to child components in React with TypeScript. Resolve Error ts(2322)

I am facing an issue where my code works perfectly in Javascript, but encounters problems when converted to Typescript. Despite the complexity of the question, it actually boils down to a simple query. I just wanted to share the functional JS code as a sol ...

Verify the login details of a distant website using Angular

Currently, I am in the process of developing a user interface for Hacker News using Angular 7. Typically, I rely on public APIs for various functionalities, but unfortunately, login services are not accessible through these APIs. In order to address this ...

Enriching Angular Tables with Custom Buttons and Actions using ng2-smart-table

I am struggling to customize the button styles in ng2-smart-table. I have tried changing the code following the steps provided in the link below, but the buttons are still not appearing as desired. Specifically, I want to update the "Edit", "Delete", "Canc ...

How to implement a material chiplist in Angular 8 using formGroup

Struggling to include a chip list of Angular material within an Ng form? Unable to add a new chip list upon button click and uncertain about displaying the value of the array added in the new chip list. Take a look at this example: https://stackblitz.com/e ...

Steps to remove the Angular workspace created in the directory C:Usersusername are as follows:

By mistake, I executed the angular command "ng new client" in the c:\users<username> directory. How can I remove it from there? I actually intended to create it in my project folder instead. ...

Angular-Serviceworker: The start URL fails to return a 200 status code when offline

Recent Versions "@angular/common": "~9.0.0" "@angular/service-worker": "~9.0.0" Exploration Utilizing the service-worker was achieved by executing ng add @angular/pwa --project [app] which triggered Lighthouse to acknowledge the web-app as a PWA. Howev ...

Unleash the power of zod by seamlessly accessing both parameters and queries

In the zod-middleware documentation, an example is provided: export async function endpointCode(req: TypedRequestBody<typeof bodySchema>, res: Response) { const typedBody = req.body; return res.json(typedBody); } This example demonstrates access ...

Creating specific union types for a bespoke React hook

There are 4 objects with both similar and different keys. The union of these objects is used for database operations as follows -> type Objects = Food | Diary | Plan | Recipe ; A Custom Pagination Hook function usePaginate (key: string, options: Option ...

Can a type be established that references a type parameter from a different line?

Exploring the Promise type with an illustration: interface Promise<T> { then<TResult1 = T, TResult2 = never>( onfulfilled?: | ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ...

Imitate a targeted ngxs store selection using ngxs

Within this component, there are two ngxs selectors being utilized: @Component({ selector: 'some-component', templateUrl: './some-component.html', styleUrls: ['./some-component.scss'], changeDetection: ChangeDetectionS ...

Encountering complications when importing TypeScript declarations

I am facing a problem with importing declarations from an extended file (I am utilizing this typing). As per the example, I have included this code in my project: import * as SockJS from 'sockjs-client'; import BaseEvent = __SockJSClient.BaseEve ...

Using an asynchronous for loop to assign a background image to a div element

I am facing an issue with setting the background image of an observable array in my Ionic application. Here is the code snippet I am using: <ion-card *ngFor="let picture of pictures$ | async;" <div class="user-image" [ngStyle]="{'background- ...

Encountered issues with the BsModalService in displaying the modal functionality

I am encountering an issue while attempting to display a modal using a service. When I call the service from a button, everything works fine. However, I encounter an error when calling it from an error handler. TypeError: Cannot read property 'attach ...

What is the process for setting up a subrouter using React Router v6?

This is the current React Router setup I am using: const router = createBrowserRouter([ { path: "/", element: ( <Page activeNav="home" > <Home /> </Page> ) }, { ...

Assess the equation twice using angular measurement

I am attempting to assess an expression that is originating from one component and being passed into another component. Here is the code snippet: Parent.component.ts parentData: any= { name: 'xyz', url: '/test?testid={{element["Te ...

Every time I try to request something on my localhost, NextJS console throws a TypeError, saying it cannot read the properties of undefined, specifically '_owner'

Update: I've noticed that these errors only appear in Chrome, while other browsers do not show them. Recently, I created a simple NextJS project by following a couple of tutorials, which also includes TypeScript. However, after running npm run dev, I ...