Steps to activate zone-conscious bluebird assurances in Angular 8

In order to make all the promises in my Angular 8 project cancelable, I embarked on a quest to find the perfect library for the job. It was during this search that I stumbled upon bluebird.js, a promising candidate ;-)

Following these guidelines on integrating bluebird with Angular's zone-aware promises, I set out to include the necessary libraries as source files in my index.html. To achieve this, I made the following adjustments in my angular.json:

"assets": [
    "src/favicon.ico",
    "src/assets",
    {
      "glob": "**/*",
      "input": "./node_modules/zone.js",
      "output": "./assets/zone.js/"
    },
    {
      "glob": "**/*",
      "input": "./node_modules/bluebird",
      "output": "./assets/bluebird/"
    }
]

I then added the following script references in my index.html:

  <script src="/assets/zone.js/dist/zone.js"></script>
  <script src="/assets/bluebird/js/browser/bluebird.js"></script>
  <script src="/assets/zone.js/dist/zone-bluebird.js"></script>
  <script>
    Zone[Zone['__symbol__']('bluebird')](Promise);
    Promise.config({cancellation: true});
  </script>

Unfortunately, despite my efforts, I encountered an error stating

Uncaught TypeError: Bluebird.onPossiblyUnhandledRejection is not a function
.

Even when attempting to move the code from my index.html to my main.ts, the same error persisted.

In a final attempt, I modified the code in my main.ts as follows:

import { Promise as Bluebird } from 'bluebird';
import 'zone.js/dist/zone-bluebird';
declare var Zone: any;
Zone[Zone['__symbol__']('bluebird')](Bluebird);
Bluebird.config({cancellation: true});

Alas, this alteration led to the error message

Zone.js has detected that ZoneAwarePromise (window|global) Promise has been overwritten.

Is there a way to successfully achieve this goal with the current versions of Angular and zone.js? Any suggestions would be greatly appreciated!

Answer №1

I made some changes to the document.

Using Angular:

In the polyfills.ts file, remember to import the zone-bluebird package.

import 'zone.js/dist/zone'; // Bundled with Angular CLI.
import 'zone.js/dist/zone-bluebird';

In the main.ts file, make sure to patch bluebird.

platformBrowserDynamic()
    .bootstrapModule(AppModule)
    .then(_ => {
import('bluebird').then(Bluebird => {const Zone = (window as any)['Zone']; Zone[Zone['__symbol__']('bluebird')](Bluebird.default);});
    })
    .catch(err => console.error(err));

After these steps, Promises will be handled by Bluebird and Bluebird.then will operate within the angular zone.

Please test this out and if you encounter any issues, feel free to inform me.

Answer №2

When I allow things to occur after bootstrapping angular, everything falls into place (I used to believe that I was implementing the "bluebird mode" too late, but it turns out it was actually too early):

platformBrowserDynamic().bootstrapModule(AppModule)
  .then(() => {
    Zone[Zone['__symbol__']('bluebird')](Bluebird);
    Bluebird.config({cancellation: true});
  })

Side note (not directly related to the original question): Unfortunately, this still doesn't allow me to cancel asynchronous functions - only cancelling promises that are directly referenced (now all Bluebirds) will trigger the onCancel callback. To achieve that, I would require something like cancelable-awaiter, but integrating it with Angular seems to be a challenge - refer to issue #1 on their repository.

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

Encountering a bug in Angular 10 while attempting to assign a value from

I am having trouble updating the role of a user. In my database, I have a user table and a role table with a ManyToMany relation. I can retrieve all the values and even the correct selected value, but I am encountering issues when trying to update it. Her ...

Exploring the most effective strategies for creating a brand-new type in TypeScript?

In the execution environment I'm working with, there are several global constants that represent different directions: TOP = 1 TOP_RIGHT = 2 RIGHT = 3 BOTTOM_RIGHT = 4 BOTTOM = 5 BOTTOM_LEFT = 6 LEFT = 7 TOP_LEFT = 8 These constants are not just ran ...

Using SignalR to implement CRUD operations within a Hub or Controller

I have been working on an Angular app that is built on top of an ASP.NET MVC application. In this project, I have a Dashboard where I showcase Average and Total numbers that are altered during Create / Update / Delete events. Usually, these events are hand ...

Having trouble importing modules from @types/node

Currently, I am in the process of developing an Electron application with Angular. My goal is to gather information about my PC and execute certain commands within the app. I have been attempting to utilize the os and child_process modules, but unfortunate ...

The render properties are not compatible with each other

I am currently using ReactQuill as a component, but I encounter this error when implementing it with Typescript. Do you have any suggestions on how to resolve this issue? The JSX element type 'ReactQuill' is not recognized as a constructor fun ...

Exploring the World of Angular6 with the Incredible Power of tinyMCE Editor

Hello, I'm looking to incorporate the tinyMCE editor into my Angular 6 application. I followed a thread that explains how to integrate it, but I ran into an issue where it says the domain is not registered. I would prefer to do this without requiring ...

Angular file upload component with customizable file size limits

I'm currently developing an upload file feature that will transmit the file via nodejs. However, I am encountering an issue related to file size. Whenever the file exceeds a few kilobytes, I encounter the following error: Error: request entity too la ...

Learning to extract information from elements within components in a flexbox using Angular

Is there a way to access the element width of child components within a parent component that utilizes flex box? I am hoping to determine if the list is overflowed so I can adjust the visibility of elements accordingly. If an overflow occurs, I would like ...

When compiling for production, I am encountering an issue where the hashed files are resulting in 404 errors for users when they try to refresh. I am unsure of the best

My Angular app is hosted on GCP storage. When I use the command ng build --prod --base-href . --output-path ~/Dev/GCP/, everything works perfectly except for one issue. If a user refreshes to get new content, they encounter 404 errors on CSS and JavaScript ...

Text box input that displays the latter portion before the initial part

Looking for assistance with showing the end of the entered text rather than the beginning in an input field. For example, the input could be "Starting portion, Ending Portion". If the input field is limited to 14 characters, instead of displaying the firs ...

Is it possible to toggle between namespace and class using parentheses?

While working with older javascript code, I stumbled upon the following snippet: // module1.js class Class { constructor() { console.log('hello') } } const exported = { Class: Class, } module.exports = exported This code is then ...

When using Angular server-side pagination with ngrx and Express in Node.js, I often encounter discrepancies in the indexing across different stacks

After successfully implementing server-side pagination in Angular, I encountered an issue where the page was set to 1 initially, but the mat-paginator component started at index 2. Despite functioning correctly when changing pages, this discrepancy puzzled ...

Using ternary operator to set multiple variables in setState

Conditional Operator for Setting State in React I am wondering if there is a way to set the state with a variable that holds the correct state value using setState method. interface state { isfiltered: array<boolean> } this.setState({ ...

Access Azure-Active Directory through cypress tests

Currently, I'm faced with the task of creating automated tests for an application that requires login to Azure Active Directory. These tests are being written using Cypress and TypeScript. In search of a solution, I am seeking advice on how to execute ...

Stop the print dialog box from appearing when using the Ctrl + P shortcut

I'm working on an Angular app and I want to prevent the print dialog from opening when pressing "Ctrl + P". To address this issue, I have implemented the following code: window.onbeforeprint = (event) => { event.stopPropagation(); cons ...

Finding all the dates within a specified date range in an Ionic 3 application

If I have a starting date of November 30, 2019 and an ending date of December 7, 2019, how can I generate a list of all the dates in between and save them in an array? I am looking to format the array like this: ["2019-11-30", "2019-11-31", "2019-12-1", ...

Integrating Constant Contact API into a Next.js application

I'm trying to integrate the Constant Contact API into my Next.js application. I've looked through the documentation, but it only provides examples for PHP and Java. How can I effectively use the authentication flow and create an app on the dashbo ...

Creating unique components with Angular2 and Ionic

Here is the HTML code for my custom component: <div> {{text}} {{percentLeft}} {{innerColor}} </div> And here is the TypeScript file for my component: import { Component, Input } from '@angular/core'; @Component({ selector: ...

Tips on displaying the entire text when hovering over it

I'm facing an issue with a select element that retrieves options from an API. The problem is that some options are too large for the text box and get cut off, making them hard to read for users. <div class="form-group my-4"> <lab ...

Unable to utilize combined data types in React properties

In my theme.interface.ts file, I defined the following 2 types: type ThemeSize = | 'px' | '1' | '1/2' | 'full' | 'fit' type ThemeWidthSpecific = 'svw' | 'lvw' | 'dvw&apos ...