Angular 14: Promise rejection not handled

Below is the function I am using:

  createVersion(data: any): Promise<any> {
    return new Promise((resolve, reject) => {
      this._httpClient
        .post(`${environment.apiUrl}/v1.0/versions`, data, {
          observe: "response",
        })
        .subscribe((response: any) => {
          resolve(response);
        }, reject);
    });
  }

When I invoke it like this:

this._versionAddService.createVersion(args).then((result) => {})

I encounter the following error:

core.mjs:7640 ERROR Error: Uncaught (in promise): OK at resolvePromise (zone.js:1213:31) at resolvePromise (zone.js:1167:17) at zone.js:1279:17 at ZoneDelegate.invokeTask (zone.js:406:31) at Object.onInvokeTask (core.mjs:26363:33) at ZoneDelegate.invokeTask (zone.js:405:60) at Zone.runTask (zone.js:178:47) at drainMicroTaskQueue (zone.js:582:35) at ZoneTask.invokeTask [as invoke] (zone.js:491:21) at invokeTask (zone.js:1600:14)

Answer №1

As noted in previous responses, there is no need to wrap it into a promise. RxJs/Observables are commonly used in Angular and you can often just keep it as an observable. The advantages include the various RxJs operators that simplify complex data transformations, making it easy to react to streams of data. Additionally, Angular facilitates subscription and unsubscription directly in the templates with the async pipe.

The error you are encountering might be due to missing the catch method (refer to createVersion2 for an example).

However, if you still prefer using promises, here's how you can implement it:

  createVersion(data: any): Promise<any> {
    return firstValueFrom(
      this._httpClient
        .post(`${'environment.apiUrl'}/v1.0/versions`, data, {
          observe: 'response',
        })
        .pipe(catchError((e) => of(`Formatted exception: ${e.error}`)))
    );
  }

  // Note that toPromise() is actually deprecated!
  createVersion2(data: any): Promise<any> {
    return this._httpClient
      .post(`${'environment.apiUrl'}/v1.0/versions`, data, {
        observe: 'response',
      })
      .toPromise()
      .catch((e) => `Formatted exception: ${e.error}`);
  }

Answer №2

To convert your Observable to a Promise in RxJS 7, you can utilize the lastValueFrom function. However, be cautious as the toPromise() method is deprecated in RxJS 7 and will be removed in RxJS 8.

Answer №3

Here is an example of how to utilize the HttpClient.post() method.

Utilizing a Service

createVersion(data: any): Observable<any> {
  const url = `${environment.apiUrl}/v1.0/versions`;
  const opts = {
    observe: "response",
  };
  return this._httpClient.post(url, data, opts);
}

This is how you can make the call.

this._versionAddService.createVersion(args).subscribe(resp => {});

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

Angular 2 - Oops! The "app-root" selector isn't finding any elements to match

Currently diving into Angular 2 with no prior experience in Angular. I came across this tutorial: . After implementing a new component called "app-people-list" and making the necessary update in index.html, I encountered the following exception. Can anyon ...

How can you dynamically disable a radio option button using Angular rendering without relying on an ID?

Is there a way to disable the male radio button without using an id, and utilizing angular rendering2? It seems like it's not working for me. I need to make this change only in the form.ts file, without altering the HTML code. form.html <label& ...

Are there any other options for handling the click event for all elements in Angular besides writing a click function for

click here for code screenshots https://i.sstatic.net/3EHOU.png see more code screenshots here https://i.sstatic.net/CcFZq.png This image displays five(5) li elements, each with the same function. However, if there are many more li elements, I am intere ...

Ensure that any modifications made to an Angular service are reflected across all components that rely on that service

I am currently in the process of replicating a platform known as Kualitee.com, which serves as a test-management tool utilized by QA Engineers. Within Kualitee, users can access multiple projects, each containing various test cases and team members. The ab ...

What is the reason behind receiving the error message "`Foo` only represents a type, but is being treated as a value here" when using `instanceof` in TypeScript?

As the creator of this code interface Foo { abcdef: number; } let x: Foo | string; if (x instanceof Foo) { // ... } Upon running this code, I encountered an error in TypeScript: 'Foo' is recognized only as a type and cannot be used a ...

How to automatically redirect in Angular 2 by utilizing router.navigate

router.navigate() seems to be working correctly in one scenario, but in another case it is redirecting to the home page unexpectedly. app.module.ts const appRoutes: Routes = [ { path: 'news/:urlLink', component: ArticlereaderComponent }, ...

Angular button router link is not functioning properly

I am currently troubleshooting the implementation of a button with a dynamic routerLink path. When using a full path, the router code functions correctly and displays the desired page. [routerLink]="['/home',{outlets:{homeOutlet:':produ ...

"Obtaining the file name rather than the file path using ngModel and ng2-file-upload: A simple guide

When a file is selected, I need to retrieve the file name and save it to the database. However, all I seem to be able to access is the fakepath of the file. //component.html <div class="col s12 file-field input-field" style="margin-left: -10px"> ...

Visual Studio 2015 is struggling to locate a specific module, yet the command line interface for

Recently, I delved into the world of TypeScript in VS2015 and so far, it has been a smooth journey. I managed to establish a structure that compiled and performed as anticipated. However, things took a turn when I attempted to incorporate npm-installed mo ...

Maximizing the Capabilities of the IIS URL Rewrite Module

Is the IIS URL rewrite module suitable for commercial use? I am looking to deploy my angular app on IIS, but my company has suggested exploring alternative options. Can the IIS URL Rewrite module not be used for commercial purposes? Are there any other a ...

What to do when faced with the Netlify Error "Dependency Installation Failure"?

Having trouble deploying a website created with react and typescript. I keep encountering an error during the initialization phase: https://i.sstatic.net/LNhFJ.png https://i.sstatic.net/w7KTo.png This is all new to me as I just started working with react ...

Dealing with Incoming HTML Content from Backend in Angular 5

My backend is sending me HTML with a Facebook login, but the observable is attempting to parse it before I can make any changes... I'm having trouble explaining this issue to search engines, so any help understanding the professional terms related to ...

Why is it that a static variable cannot be accessed using the `this` keyword in a static method when the static method is called in any route's controller in NODEJS?

Is it possible to access static variables in a static method using the 'this' keyword? The answer is yes, but there seems to be an issue when passing that static method in any route. The 'this' keyword refers to the class, yet its value ...

An error may occur when Typescript is instantiated with a varying subtype of constraint

I am encountering the "could be instantiated with a different subtype of constraint" error when trying to return a result that should match the expected type of a function. Despite removing irrelevant details, I'm struggling to pinpoint what exactly I ...

`How can I successfully publish an Angular2 Component to npm while keeping the templateUrl html file separate?`

I have embarked on the task of creating an Angular2 library that includes various Components. My goal is to package this library as an npm module, allowing me to easily install and utilize it in my other Angular2 projects using npm install. To achieve thi ...

What techniques can I use to adjust the size of an image through zooming in and out?

In my custom gallery component, the crucial code section looks like this: <Gallery> <Header> <img src={galleryIcon} alt='Galley icon' /> <h1>My Gallery</h1> </Header> ...

Structuring your Angular 6 application and server project

What is the recommended project structure when developing an Angular 6 application and an API server that need to share type definitions? For example: On the client side: this.httpService.get<Hero[]>(apiUrl + '/heroes') On the server si ...

Is there a way to ensure that in angular 2+, when clicking on a button with the same route as the current page, the page will reload?

Why would I even consider complaining about this? You’re already here, aren’t you? I have a couple of reasons why a reload needs to happen, but for now I’ll just mention one. 1) When my user clicks on a link, they may not realize it's the same ...

Having trouble with NPM build getting stuck in Azure DevOps

There seems to be a problem similar to the one discussed in this question: npm run build hangs indefinitely on azure. Our build process has been functioning smoothly for several months. However, we are currently facing an issue where npm build is failing ...

The spinner failed to appear within 2000 milliseconds

After submitting the form, I want to display a spinner for 2000 milliseconds. However, my implementation using the setTimeout function is not working as expected. import { Component, OnInit } from '@angu ...