finally block in angular 2 promise

Dmehro picture Dmehro · Nov 16, 2016 · Viewed 7.5k times · Source

I observe that In angular 2 there is no finally block for promise API

angular 1 :

 loadUsers() {
  fetch('/api/users').then((response) => {
    return response.json();
  }).then((data) => {
    this.users = data;
  }).catch((ex) => {
    console.error('Error fetching users', ex);
  }).finally(() => {
     this.userLoaded = true;
};

Assuming I have to do same thing in angular 2

How to add finally block in angular 2 promise , as of now there are only then & catch blocks available in angular 2. If not finally then is there any way to add cleanup code after execution of each method , where do i write code to do finally block activities ?

Answer

Tom Spencer picture Tom Spencer · Dec 14, 2016

The easiest way to do this is to use the promise.finally shim.

  • Add it with npm install --save promise.prototype.finally
  • Add the typings: npm install --save-dev @types/promise.prototype.finally
  • In your main class, before bootstrapping the application, add the following code:
import { shim } from 'promise.prototype.finally';
shim();

You should now be able to use finally on your promises.