RxJS equivalent of a 'finally' callback for Promises

In my component, I have a process that retrieves data from an API. To indicate whether the data is being loaded or not, I use a member variable called loading. Once the data retrieval process is complete, I set loading to false to hide the loading icon. This should happen even if there was an error during the process.

Currently, my implementation looks like this:

export class MyComponent implements OnInit {

  loading = true;
  data;

  constructor(private dataService: DataService) { }

  ngOnInit() {
    this.dataService.getData().subscribe(data => {
      this.data = data;
      this.loading = false;
    },
    () => {
      this.loading = false;
    });
  }

}

I'm exploring ways to avoid repeating this.loading = false. If I were working with Promises, I would utilize the Promise.finally() callback for this purpose - however, I am using RxJS. Is there an equivalent in RxJS or a more efficient way to achieve this?

Answer №1

Starting from RXJS version 5.5, it is recommended to implement the "finalize" operator:

ngOnInit() {
  this.dataService.getData()
  .pipe(
    finalize(() => this.loading = false)
  )
  .subscribe(data => {
    this.data = data;
  });
}

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

JavaScript - Deleting the last element of an array

I have currently integrated a third-party API to visualize data using Highcharts. This external API provides data specific to the current month, such as March, April, May, and so on. graphArrOne contains an array with 251 elements. graphArrTwo contains ...

Typescript compiler still processing lib files despite setting 'skipLibCheck' to true

Currently, I am working on a project that involves a monorepo with two workspaces (api and frontEnd). Recently, there was an upgrade from Node V10 to V16, and the migration process is almost complete. While I am able to run it locally, I am facing issues w ...

Is there a method to incorporate the ".then callback" into useEffect?

Is there a way to utilize the ".then callback" to log the word "frog"? I am interested in viewing my token within the async-storage. Once I have obtained my token, I need to append it to the header of a fetch call. Does anyone know how to accomplish this? ...

Implement angular translation as an argument for a notification function

Can anyone help me figure out how to pass a string message as a parameter to my AddRemoveUserOfGroupGeneral function? I am using matToolTip without any issues, but I'm struggling to pass it to my function: <button mat-raised-button color="prim ...

ng-class remains stagnant as ng-if dynamically updates when tab is no longer in focus

Implementing an interceptor to display a loader while making API calls can come with its challenges. In this case, two API requests are set at intervals of every 60 seconds using $interval. When the page is in focus, the loader functions correctly by showi ...

Node and Socket.IO - Personalized messaging (one-on-one)

I'm in the process of developing a one-on-one chat feature using Socket.IO and Express to enable private messaging between users. The main issue at hand is: I am looking for a way to send a private message to a specific socket.id while ensuring that ...

Error TS2345: The type '{ type: "mouseWheel"; }' cannot be assigned to the parameter of type 'MouseInputEvent | MouseWheelInputEvent | KeyboardInputEvent'

I've integrated the sendInputEvent method into BrowserView: view.webContents.sendInputEvent({type: 'keyDown', keyCode: 'C'}) In the rendering page of BrowserWindow, I've added: window.addEventListener('keydown', ...

Should we consider using extra url query parameters as a legitimate method to avoid caching or enforce the updating of css/js files?

Is it acceptable to include extra URL query parameters in order to avoid caching or enforce the updating of CSS/JS files? /style.css?v=1 Or would it be preferable to rename the file/directory instead? /style.1.css I've heard that this could potent ...

Unable to execute JS script to navigate back to prior page with webdriver

Here is my code snippet: JavascriptExecutor jse = (JavascriptExecutor)driver; jse.executeScript("window.history.go(-1);"); The code above isn't working. I've tried casting the webdriver instance but it doesn't work every time. I prefer not ...

After upgrading from Angular 2.x to 4.x, the error "Property 'emit' is not found on type 'People'" is encountered

I am encountering an issue with a class definition: import * as events from 'events'; export class People extends events.EventEmitter implements IMarkTool{ public static REMOVE = "REMOVE"; public static INVITE = "invite"; socketServi ...

Importing a MATLAB table file into a Node.js environment and converting it into an array

Currently in the process of setting up a test server for a Web-Application, where fake data needs to be transmitted via a Websocket. The fake data is stored in a MATLAB table file (.mat), which essentially consists of a 4000*192 array. My goal is to conver ...

Run both a .Net webapi and an Angular4 application simultaneously within the same IIS Application hosting environment

I've come up with a solution that involves two main projects: The frontend, which is an Angular4 application The backend, which is a .Net Core webapi Everything works flawlessly on my local system. I have set up two separate applications in IIS - o ...

What methods can I use to analyze the integrity of the data's structure?

Currently working on an API using NestJS and typeorm. I am in need of a way to verify the format of the data being returned to clients who make requests to it. For instance, when accessing the /players route, I expect the data to have a specific structure ...

VueJS: Connecting data to Components

I'm struggling to articulate this question clearly, and the documentation isn't providing the answers I need. Essentially, in my dataset, I have an array with two values that represent the day of the week index. I want to create a custom range c ...

What is the method for defining distinct parameters for nested functions in AngularJS?

When using AngularJS, what happens when a parent function encapsulates a child function that includes parameters not present in the parent? In this scenario illustrated below with the green arrow representing the parent function without any parameters, an ...

What's the best way to invoke a function from a different JS file or create a custom event in JQuery that includes a parameter as a data object?

I am facing an issue while using requireJS to call a function from a required JS file. In my main app.js "controller", I have included (plugin)app.js, which contains all plugin configurations and related functions. The snippet below is from app.js defin ...

Unable to retrieve share count data from the AddThis API using the <script/> tag

After spending several hours attempting to solve this issue on my own, I have decided to reach out to the experts in the Stackoverflow community. The script code I am using is functioning correctly for the Facebook API but seems to be encountering issues ...

Error: Unable to execute $(...).stellar since it is not a recognized function

Having some trouble implementing the stellar plugin. I've included all the necessary js, but keep getting an error in the dev tools console: 'Uncaught TypeError: $(...).stellar is not a function'. Here's what I have in the head tags: ...

I encounter an error when I link or embed a middleware within another

I am facing an issue while trying to implement a nested middleware within another middleware. Upon calling the nested middleware, I encounter the following error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client Below ...

Stop auto-scrolling to the top when triggering a getJSON request

I'm feeling really puzzled at the moment. Here is the snippet of code I am struggling with: $("#combinations").on("change", "input", function (e) { e.preventDefault(); console.log(e) var $button, $row, $group, $form, $barcode ...