Dealing with Errors - Utilizing Observable.forkJoin with multiple Observable instances in an Angular2 application

One of my Angular applications has two objects, Observable<Object1[]> and Observable<Object2[]>, that call different APIs in the resolver:

resolve(): Observable<[Array<Object1>, Array<Object2>]> {
    const object1 = this.bookingService.executeService1(); // returns Observable<Object1[]>

    const object2 = this.bookingService.executeService2(); // returns Observable<Object2[]>

    return Observable.forkJoin(object1, object2); // Error handling needed
}

Everything runs smoothly until an error occurs. When an error happens, it appears as Uncaught in the console. I've tested the service API using tools like Postman, and it functions correctly there.

I attempted to catch the error like this:

return Observable.forkJoin(object1, object2)
  .catch(error => {
    console.log('error', error);
  });

Unfortunately, this approach did not resolve the issue.

If you have any suggestions on how to properly handle errors in the resolver with Observable.forkJoin(), please let me know.

Answer №1

If you're seeking a solution to your issue, the forkJoin's learnrxjs.io page is where you should look. Visit this link for more information.

It's important to note that if an error occurs in any of the inner observables provided to forkJoin, you may lose the value of other observables that have already completed or would complete. Make sure to handle errors properly on the inner observable to avoid this issue. If your main concern is that all inner observables complete successfully, consider catching the error on the outer level.

const example = forkJoin(
  //emit 'Hello' immediately
  of('Hello'),
  //emit 'World' after 1 second
  of('World').pipe(delay(1000)),
  // throw error
  _throw('This will error')
).pipe(catchError(error => of(error)));

Answer №2

Feel free to utilize it as detailed in the following resource: RxJS Angular2 handling 404 in Observable.forkjoin.

I trust that this information proves beneficial to you!

Answer №3

To identify errors, you can use the following method:


    let first = Observable.of({value : 1}); 
    let second = Observable.throw({value : 2});
    Observable.forkJoin(first, second)
              .subscribe((res: Array<any>) => console.log(res),
              (error) => {
                console.log(error);  //{value: 2} will be shown here
              });

In case of separate observables, you can catch errors individually and return another observable like this.


    return Observable.forkJoin(
        this.http.get('/url')
            .map((res:Response) => res.json())
            .catch(res:Response => Observable.of({}),
        this.http.get('/url2')
            .map((res:Response) => res.json())
            .catch(res:Response => Observable.of({}),
    );

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 6: Harnessing the Power of RouterLinks

Can you navigate to a different section of another page using the defined ID without having to reload the entire page? ...

Is it possible to close a tab while the chrome extension popup is still active?

I am currently developing a Chrome extension that reads the content of the current tab and performs a heavy task on the backend. If I were to close the tab while the process is ongoing, how can I allow the user to do so without waiting for the task to fi ...

Issue with TypeScript: Rxjs uses different syntax for setTimeout compared to what is defined in @types/node

System Information: Node version: v11.7.0 RxJS version: 6.3.3 @types/node version: 8.10.45 tsc version: 3.2.4 During the execution of tsc, it appears that there is an issue within Rxjs where the setTimeout function is being called without specifying th ...

Refresh the main state by integrating the feature state using NGRX

A question arises regarding my app that utilizes ngrx to display blogs. Here is an overview of the main root state: import { Blog } from '../models/blog'; export interface AppState { readonly loaded: boolean; readonly blogs: {[key:number]: ...

Employing multiple subscriptions within a function

I am facing an issue in my Angular application where I am trying to display a detailed summary of the sales for a specific drink using the DrinkDetailComponent. However, upon initializing the component, only one backend call is being made to retrieve infor ...

Tips for including a sequelize getter in a model instance?

I'm currently struggling to add a getter to the name field of the Company model object in my project. Despite trying various approaches, I haven't had any success so far. Unfortunately, I also couldn't find a suitable example to guide me thr ...

The utility of commander.js demonstrated in a straightforward example: utilizing a single file argument

Many developers rely on the commander npm package for command-line parsing. I am considering using it as well due to its advanced functionality, such as commands, help, and option flags. For my initial program version, I only require commander to parse ar ...

DataGrid parameters in Material UI are only considering the final value in the table

I am working with a Data Grid table containing user information, and I want to include a sub-menu of options in the last column that opens up a modal for each user. However, I am facing an issue where only the data from the final row in the table is being ...

Setting the value of a select input in a reactive form

I am facing an issue with autofilling the select input on my form. Even though I've written the code, the value of the select field remains empty when the form loads. In my code, I have declared a static array of objects called extensions which conta ...

AngularJS or Angular 2: Reorganize the JSON data once the 'http' response is received

Updated: [{ "name": "b1", "category": "X1", "amount": 15 }, { "name": "b3", "category": "X1", "amount": 35 }, { "name": "b2", "category": "X1", "amount": 25 }, { "name": "b1", "category": "X2", "amount": 150 }, { "name": "b6" ...

Can an Angular Component be displayed using a Serverless function like Lambda on AWS?

I have a single-page application developed in JavaScript using the Angular 6 Framework, and I am interested in dynamically rendering an Angular Component that is hosted on a remote server. Currently, I am utilizing viewContainerRef to dynamically render ...

Sharing a Promise between Two Service Calls within Angular

Currently, I am making a service call to the backend to save an object and expecting a number to be returned via a promise. Here is how the call looks: saveTcTemplate(item: ITermsConditionsTemplate): ng.IPromise<number> { item.modifiedDa ...

Check the type of the indexed value

I need help with a standard interface: interface IProps<T> { item: T; key: keyof T; } Is there a way to guarantee that item[key] is either a string or number so it can be used as an index for Record<string | number, string>? My codeba ...

Having trouble implementing a CSS style for a Kendo-checkbox within a Kendo-treeview component

I am facing a The issue I am encountering is that while the CSS for k-treeview is being applied from the scss file, it is not being applied for the kendo-checkbox I attempted to resolve the problem by using the following code: <kendo-treeview ...

Ways to adjust the color of an angular mat-radio-button when it is in the unchecked state

Is there a way to change the color of a mat-radio-button when it is NOT checked without having to modify the entire theme? I've been searching for an answer for quite some time now and I'm starting to wonder if it's even possible. Using CSS ...

A guide on incorporating Union Types in TypeScript

Currently utilizing typescript in a particular project where union types are necessary. However, encountering perplexing error messages that I am unsure how to resolve. Take into consideration the type definition below: type body = { [_: string]: | & ...

Why does Angular keep changing my request method to OPTIONS?

I've been working on setting up a JWT Interceptor in Angular. Following the example provided here, I implemented my JWT interceptor using the code snippet below: import { HttpInterceptor, HttpRequest, HttpEvent, HttpHandler, HttpHeaders } from &apos ...

Service consumption across various components is failing to function as intended

I'm working on implementing a side navigation bar and content div. The goal is to display the innerText of the selected navigation item in the content div whenever an element in the side nav is clicked. Below is my current code setup: sidenav.compone ...

Error encountered while retrieving the cropped image, atob function was unable to execute

I am currently facing an issue with saving a cropped image in Chrome. When I try to save it, the download fails when using the Download button that I added to the page. I have successfully used ngx-image-cropper for cropping the image as intended. The cro ...

Having trouble connecting to the API due to the error "No Access-Control-Allow-Origin" in Angular 2

I am new to working with Angular2 and I'm currently facing a challenge in implementing authentication for an app using username and password login credentials. Unfortunately, I keep encountering the error message "No Access-Control-Allow-Origin". htt ...