Angular - pipe function disrupts the flow of execution

Here is the code snippet in question:

 subscriber.pipe(
        switchMap(data => {
            this.getData().pipe(
                map(() => res),
                catchError(error => {
                    return of(null);
                })
            );
        }),
        switchMap(data => {

        })

    ).subscribe();

If an error occurs in the first switchMap and null is returned, the next switchMap will receive null data. However, I would like to halt the execution if the first switchMap goes into the catchError block, preventing the second switchMap from being executed. Is there a way to achieve this?

Answer №1

Ensure to place the catchError method at the conclusion of the pipe.

subscriber.pipe(
   switchMap(data => {
       ...
   }),
   switchMap(data => {
       ...
   }),
   catchError(error => {
       return of(null);
   })
).subscribe(val => {
    // val will be null in case of any errors
})

Answer №2

In this scenario, employing a filter seems like the most suitable solution. By setting up error handling to return null and utilizing a filter after the initial switchMap, you can effectively filter out any null values that may occur.

subscriber.pipe(
       switchMap(data => {
          this.getData().pipe(
             map(() => res),
             catchError(error => {
                 return null;
             })
          );
       }),
       filter(v => v),
       switchMap(data => {
    
       })
    
    ).subscribe();

Answer №3

RxJS # EMPTY Operator

The EMPTY operator in RxJS creates an observable that emits nothing and completes immediately.

subscriber.pipe(
       switchMap(data => {
          this.fetchData().pipe(
             map(() => response),
             catchError(_ => EMPTY)
          );
       }),
       switchMap(data => {
    
       })
    
    ).subscribe();

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

How can the id from a post response be obtained in Angular 7 when using json-server?

When utilizing the http options below: const httpOptions: any = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }), observe: 'response' }; I execute an http post to a json-server endpoint like this: ...

Bringing in Leaflet for Angular 2 and beyond

Hello there! I'm currently diving into the world of Angular 2 and wanting to figure out how to integrate Leafletjs with it. My goal is to set up Leafletjs without having to directly include JS and CSS in my index.html file. Additionally, I want to ens ...

Setting up a route based on URL parameters from various applications

My Java application has 5 links, and I want each link to open a specific Angular form based on the parameters passed through them. How can I configure my routes in Angular to achieve this functionality? ...

Utilizing Gulp to Convert TypeScript Exports into a JSON File

I have a set of TypeScript files, some of which export a specific variable - named APIS - which contains an array of objects. My goal is to extract the values from all of these exports and save them into a JSON file using Gulp. Let's consider a direc ...

AngularJS - Unusual outcomes observed while utilizing $watch on a variable from an external AngularJS service

Within the constructor of my controllers, I execute the following function: constructor(private $scope, private $log : ng.ILogService, private lobbyStorage, private socketService) { this.init(); } private init(){ this.lobbyData = []; this.initial ...

Re-activate video playback after 30 seconds of user inactivity (using RxJs)

My intention is to provide a brief explanation of the functionality I am looking for. Essentially, when a video is playing, I want it to pause if a user clicks on it, allowing them to do something else. Then, after 30 seconds of idle time, I need the video ...

Error: SvelteKit server-side rendering encountered a TypeError when trying to fetch data. Unfortunately, Express is not providing a clear TypeScript stack trace

I've been monitoring the logs of the SvelteKit SSR server using adapter-node. After customizing the server.js to utilize Express instead of Polka, I noticed some errors occurring, particularly when the fetch() function attempts to retrieve data from ...

Is it possible to validate a template-driven form without using the model-driven approach?

Attempting to validate a template-driven form in Angular without two-way data binding has proved to be challenging. I have successfully implemented validation using [(ngModel)], but running into an error when trying to validate the form without the MODEL p ...

Modifying the State in a Class Component

private readonly maxSizeOfDownloadedFiles: number = 1000000; state = { totalSum: this.maxSizeOfDownloadedFiles }; handleCallback = () => { this.setState({ totalSum: 12 }) alert('totalSum ' + this.state.totalSum); }; Upon executing the ...

What is preventing me from applying styles to the first word in my Angular ngFor iteration?

I'm currently attempting to customize the initial word of a string within my Angular ngFor loop. Strangely, the class gets applied but the style defined in my CSS file is not. Inline styling also does not seem to work - any ideas why? This is the CSS ...

Find the identifier that does not currently exist in the collection of objects

There is a situation where I have an array and an object that consists of arrays of ids, which are essentially permission objects. My goal now is to extract the ids that do not exist in the given object. Can someone assist me with devising the necessary l ...

What is the proper way to call document methods, like getElementByID, in a tsx file?

I am currently in the process of converting plain JavaScript files to TypeScript within a React application. However, I am facing an error with document when using methods like document.getElementById("login-username"). Can you guide me on how to referen ...

What is the best way to recycle a single modal in Ionic?

Apologies for the vague title, but I'm facing an issue with creating a single modal to display data from multiple clickable elements, rather than having separate modals for each element. For example, when I click on item 1, its data should be shown in ...

Having trouble retrieving the `Content-Disposition` information from the backend response

I've been attempting to retrieve the value of Content-Disposition from the backend response, but unfortunately, I have not been successful. Here is the code I have been working with: public getQuoteImage(sharedQuote):Observable<any> { retu ...

Exploring the return type of the `within` function in TypeScript Library

I have helpers set up for my React tests using the testing library: const getSomething = (name: string, container: Screen | any = screen) { return container.getByRole('someRole', { name: name }) } The container can be either the default screen ...

Issue with NullInjectorError: Failure to provide a custom component - Attempting to add to providers without success

I keep encountering errors during my test attempts... Despite looking into similar issues, I am still facing problems even after adding my custom LoginComponent to app.module.ts providers. It is already included in the imports section. app.module.ts @Ng ...

TypeScript: empty JSON response

I am encountering an issue with the JSON data being blank in the code below. The class is defined as follows: export class Account { public amount: string; public name: string; constructor(amount: string, name: string) { this.amount = amount; t ...

What's with all the requests for loaders on every single route?

I'm in the process of setting up a new Remix Project and I'm experimenting with nested routing. However, no matter which route I navigate to, I keep encountering the same error: 'You made a GET request to "/", but did not provide a `loader` ...

Exploring Angular 8: Connecting elements to an array filled with objects

My goal is to achieve the following: https://i.sstatic.net/TQeKN.png In my form, I have 2 fields: description and price. When the plus button is clicked, additional input fields (Input 2 and Price 2) are generated dynamically. I want to bind these field ...

Using NestJS to populate data will only populate the first element

I have a Mongoose schema in NestJS structured like this: ... @Prop() casinoAmount: number; @Prop() gameHyperLink: string; @Prop() casinoHyperLink: string; @Prop({ type: Types.ObjectId, ref: 'Game' }) games: Game[]; } I'm t ...