Home > database >  angular 14: Uncaught in promise
angular 14: Uncaught in promise

Time:10-07

I have the below function

  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 call it

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

i get this 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)

CodePudding user response:

If you are using RxJS 7 you could use lastValueFrom function that will convert your Observable to a Promise. If you are running on older versions you could use the toPromise(). Careful! This is deprecated in RxJS 7 and in RxJS 8 is going to be gone.

CodePudding user response:

This is how you should use HttpClient.post().

Service

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

Call it like this.

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

CodePudding user response:

As mentioned in the other answers you don't need to wrap it into a promise. RxJs/Observables is heavily used in Angular and often you will just keep as it observable. The benefits are e.g. all the great RxJs operators which makes it easy to do complex data transformations, easy to react to streams of data and then Angular also makes it easy to subscribe and unsubscribe directly in the templates with the async pipe and so on. The error you see may be because you are missing the catch method (see for createVersion2.)

But here is how you can do it if you want it as a promise:

  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}`)))
    );
  }

  // toPrmoise() 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}`); 
  }
  • Related