What is the proper method for integrating a loader into an observable HTTP request?

I need to implement a "loading" variable for my login method:

Here is the current login method:

public login(authDetails:any):any{
  return this.http.post<any>('https://myapi.com/session', authDetails).pipe(
    map(response  => {
        this.sessionStore.update(response.data.attributes)
      }
    )
  )
}

The loading variable can be set using

this.sessionStore.setLoading(true/false)
.

While it's clear where to call setLoading(false), I am unsure about where to put setLoading(true) since the subscribe method will be called externally.

Identifying when loading should be turned off is straightforward

(Update: it's not: see the comments below. In summary, the .setLoading(false) call should happen in a .finalize method to ensure it also happens during errors)

public login(authDetails:any):any{
  return this.http.post<any>('https://myapi.com/session', authDetails).pipe(
    map(response  => {
        this.sessionStore.update(response.data.attributes)

         // setLoading to false here:
        this.sessionStore.setLoading(false); // <= Loading ended
      }
    )
  )
}

Where should loading be switched on?

.setLoading(true) needs to be triggered when the observable is subscribed to. I want to maintain the loading behavior within this function for reusability, but I'm uncertain how to sync calling setLoading(true) with the subscription to the observable.

In the past, an onSubscribe event might have been used, but I suspect that's not the RxJS way.

Do you need to wait for .subscribe() or is it implicit?

Should I simply place it at the beginning of the method? I hesitate because it's not explicitly clear if the code has been subscribed to at that point.

public login(authDetails:any):any{

  this.sessionStore.setLoading(true); // <= Correct?!

  return this.http.post<any>('https://myapi.com/session', authDetails).pipe(
    map(response  => {
        this.sessionStore.update(response.data.attributes)
        this.sessionStore.setLoading(false); // <= Loading ended
      }
    )
  )
}

Answer №1

Before making the call to the observable method, you have the option to start your process and then conclude it within the finalize() method. This allows you to handle both successful responses and errors received from the server effectively. To learn more about how to use this method, feel free to visit the following link: Observable Finally on Subscribe

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

Why does the property of {{hero.name}} function properly in a <h> tag but not in an <img> tag?

Within this template, the code below functions correctly: <h3>{{hero.name}}</h3> It also works for: <a routerLink="/details/{{hero.id}}">{{hero.name}}</a> However, there seems to be an issue with the following image path ...

What is the best way to ensure that the operations are not completed until they finish their work using RX

Is there a way to make RXJS wait until it finishes its work? Here is the function I am using: getLastOrderBeta() { return this.db.list(`Ring/${localStorage.getItem('localstorage')}`, { query: { equalTo: fa ...

Is it possible to apply filters to individual columns in a dynamic mat table using Angular?

Does anyone know how to add a filter for each dynamic column in an Angular Material table? I've only found solutions for static headers, but my table headers are constantly changing. I'm looking for something similar to this example: https://i.st ...

Is it possible for me to define TypeScript interfaces to be used in vanilla JavaScript projects within VSCode?

While using the MS VisualCode editor, I am attempting to implement type checking in my Javascript code. I want to maintain the flexibility of Javascript while also benefiting from type checking interfaces and data structures. Based on the vscode documenta ...

Craft fresh items within HTTP request mapping

I am currently working on a function that subscribes to a search api. Within the map function, my goal is to transform items into objects. I haven't encountered any errors in my code, but the response always turns out empty. Here's the snippet o ...

When a shared service is used for parent component binding with *ngIf, the update is not reflected when triggered from the child component

I have two components, a main parent component and a child component. The parent component contains a menu. Even when the child component says this.service.isMenuVisible(false), the menu remains visible in the parent component without any errors being thro ...

Tips for sending data returned asynchronously from an Observable in Angular from a Child component to its Parent

I am facing a challenge passing Async data from child to parent component. When I try to access console.log(this.values) within the ngAfterViewInit() method in the parent component's HTML page load, it returns an empty value. However, upon clicking th ...

What is the process for adjusting the color of a mat-divider?

Has anyone been successful in changing the color of mat-divider? I attempted the following but had no luck: component.html <mat-divider class="material-devider"></mat-divider> component.scss .material-devider { color: red } ...

Unable to display Md-checkbox component in Angular 2

I have been attempting to display a checkbox within my Angular 2 application, however, it doesn't seem to be appearing. What are some potential reasons for this issue? <md-checkbox [checked]="true">Unchecked</md-checkbox> <md-checkbox ...

Experiencing unexpected behavior with Next.JS getStaticProps functionality

I am currently working on a website where I want to display dynamic feedback as cards. However, my fetchData variable within the Home function is always returning undefined. Here's the code snippet I have tried: import UserCard from "../component ...

Disabling end date options in an Angular Material date range picker based on the selected start date

I am currently using an Angular Material 15 date range picker and it is functioning properly. I can select a start date and an end date, which are then displayed in the associated input fields. However, I am facing an issue with setting the minimum and m ...

Troubleshooting Angular 2 routes failing to function post aot compilation deployment

Currently, I am implementing RouterModule in my project and have the following configuration in my app.module.ts file: const appRoutes: Routes = [ { path: '', redirectTo: 'mainMenu', pathMatch: 'full' }, { path: 'mainMen ...

Utilizing internationalization and next/image in next.config.js alongside TypeScript

Currently, I am in the process of developing a miniature application using TypeScript within NextJS now that support for TypeScript comes standard in Next.js. Additionally, my aim is to integrate two recently introduced features: Image Component and Image ...

The ngModel directive is present here

In my Angular project, I've observed the use of two different syntaxes for binding ngModel: [(ngModel)]="this.properties.offerValue" and [(ngModel)]="properties.offerValue". Although they appear to function identically, it has sparked my curiosity ab ...

Exploring Rxjs repeatwhen with a delay in action

I'm struggling to understand how repeatWhen and delay() work together. If you want to see my issue in action, click on this link and make sure to open the console. I tried using takeWhile to stop the repeatWhen stream before it gets to the delay ope ...

Child component in Angular not receiving updated variable values when being called from parent component

Struggling with dynamically updating the style of an element. I've added margins on top of an image by creating a child component to handle it. I invoke a function on the child component that calculates the margins and sets a variable. This is how t ...

Using currency symbols in Angular 2

I'm currently in Australia and trying to display some currency values. I have the following code: {{ portfolio.currentValue | currency : 'AUD' : true : '4.0' }} However, the result I am getting is A$1,300,000. Is there a way to c ...

There are no specifications available for the project that is located in the same workspace as the main

I have been given the responsibility of testing an application for a company. When I execute the main project using "ng test", it runs smoothly and detects all its test suites. However, when I attempt to run another project within the same workspace named ...

Understanding the concept of dynamic arrays in Typescript?

In my current project, I have a specific requirement that involves reading an auto-generated value "x" in a loop for a certain number of times (let's say "n"). I need to store these auto-generated values of "x" so that I can later use them for perform ...

Verifying the Presence of an Image in the Public Directory of Next JS

My TypeScript Next.js project contains a large number of images in the public folder. I am wondering if there is a way to verify the existence of an image before utilizing the <Image /> component from next/image. I have managed to achieve this using ...