If the outer observable encounters an error, make sure to forcefully call the inner observable within the switchMap

Here is my code:

    return this.userService.getPosition().pipe(
      switchMap(() => {
        return this.get('/places', { point: this.userService.coords });
      }),
    );

Sometimes, the position cannot be retrieved, for example if there is no https in Google Chrome or if the user does not allow it.

In such cases, I still need to execute

return this.get('/places', { point: this.userService.coords });

However, in this scenario, this.userService.coord will have a value of null.

This is how the service code looks like:

export class UserService {
  constructor() {}

  coords: Coordinates;

  getPosition(): Observable<any> {
    return new Observable(observer => {
      if (window.navigator && window.navigator.geolocation) {
        window.navigator.geolocation.getCurrentPosition(
          position => {
            this.coords = [position.coords.latitude, position.coords.longitude];
            observer.next(this.coords);
            observer.complete();
          },
          error => observer.error(error),
        );
      } else {
        this.coords = null;
        observer.error('Unsupported Browser');
      }
    });
  }
}

Currently, if the outer observable returns an error, the inner observable is not executed.

Answer №1

If you encounter an error, you can make use of the catchError method.

Without knowing the specific data types you are working with, a general example would look something like this:

For instance:

return this.userService.getPosition().pipe(
  catchError((error) => {
      // We have caught the error and instructing the pipeline to proceed using the specified value.
      return of(this.userService.coords);
  }),
  switchMap(point => {
    // This line will execute regardless of any errors that occurred earlier in the pipeline.
    return this.get('/places', { point: point });
  }),
);

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

Implementing the same concept yet yielding diverse variations?

I'm a bit confused as to why a1 is evaluated as false while a2 is considered to be of type boolean. Can someone explain the reasoning behind this discrepancy? type Includes<T extends readonly any[], U> = U extends T[number] ? true : false; type ...

Angular - optimize performance of vm-ware datagrid by using clrDgRefresh with debounce for improved

Is there a way to delay an event triggered by the clarity datagrid until after the user has finished typing before fetching data from the backend? My angular 6 application uses the grid, and I bind the event to a function in my setup like this: <clr-da ...

When a card is clicked in the parent component, data is sent to the child component in Angular. The card contains an image, name, ID,

How can I pass data from a parent component (nfts) to a child component (main) when a card is clicked? The card contains images, ids, names, and more information. I've attempted using @Input() but haven't been able to receive the value in the ch ...

Trouble arises when selecting shapes in Angular 6 with FabricJS

Currently, I am experimenting with fabricjs and drawing different shapes. Interestingly, when I draw the shapes, they appear accurately on the canvas. However, when I try to switch to selection mode, I encounter an issue where I am unable to select the ind ...

Is it necessary for @Input() to come before @ViewChild in Angular components? And what is the reason

Within my ImageUploaderComponent, I have defined an @Input variable and an @ViewChild element. export class ImageUploaderComponent implements OnInit { @Input() canvasheight: number; @ViewChild('cropper', undefined) ... } Interestingly, th ...

Tips for Integrating an Angular App into a Different Website

I have an Angular application hosted at www.A.com, My client has a website hosted at www.B.com I am looking to enable my client to embed the Angular app on their webpage without physically copying the application files. I want them to simply add some HTML ...

The art of expanding Angular's HTTP client functionality

I understand that the following code is not valid in Angular, but I am using it for visual demonstration purposes. My goal is to enhance the Angular HTTP client by adding custom headers. I envision creating a class like this, where I extend the Angular h ...

Combining an external class with a namespace in TypeScript

Valid Script Code: class InputField { } namespace InputField { export enum Types { text = "text", number = "number" } } export { InputField }; Invalid Script Code: import InputField from "@Controls/InputFields/Inp ...

How can one execute a function within an HTML attribute value using Angular?

I am currently attempting to use the weatherToFontAwesomeIcon(weatherDescription: string) function directly within the HTML file for this component. My goal is to showcase a specific FontAwesome icon based on the weather response from the API. import { Cur ...

In TypeScript, inferring argument types

Here is the code snippet in question: type Inferred<T> = T extends (...args: (infer UnionType)[]) => any ? UnionType : never function f(first: 'first', second: 'second', bool: boolean) {} type T = Inferred<typeof f> // ...

Angular: Transforming input types

When the div is pressed, it triggers a function that changes the type of input. There are two password inputs that are changed to text when the function is triggered. Issue Error 1: 'password' may be null. If I enter '' in the password ...

Instance property value driven class property type guard

Is it possible to create a class example that can determine the config type based on the value of animalType instance: enum Animal { BIRD = 'bird', DOG = 'dog', } type Base = { id: number } // Object example type Smth = Base & ...

Challenges encountered during the setup of Angular 2

Every time I attempt to setup Angular 2 on my computer, I keep encountering this error: 244 error node v4.3.1 245 error npm v2.14.12 246 error code ENOTFOUND 247 error errno ENOTFOUND 248 error syscall getaddrinfo 249 error network getaddrinfo ENOTFOUND ...

Examining Axios HttpService piping through a NestJS middleware in a unit test

A middleware function retrieves a JSON document from a microservice endpoint and appends it to the request. The good path test is successful, but I'm struggling to make the bad path test throw a ForbiddenException and stop it from invoking next(). W ...

Setting up AngularJS can be a pain

Greetings, my name is Rahim. While setting up AngularCLI, I ran into the following issue: 'ng' is not recognized as an internal or external command, operable program or batch file. C:\Users\ASUS ROG>ng --version 'ng' is ...

Creating various subtypes for graphql-codegen

Currently, I am utilizing the typescript-operations package within the framework of the graphql-codegen library. Previously, I was accustomed to using Apollo's deprecated codegen and appreciated how it exported types seamlessly. For example, let&apos ...

Establish a permanent code folding feature in the Monaco editor for enhanced text organization

I need help implementing persistent code folding on the Monaco editor. Specifically, I am unsure about: how to extract the view state when it changes; storing it in localstorage; and then restoring it when Monaco is loaded. Although I am aware of saveVie ...

Tips on effectively binding ngx-mat-select-search to an array and setting up an output emitter for selection changes

I am implementing ngx-mat-select-search to create a multi-select dropdown with search functionality. My aim is to develop a component that: Receives a list of values to display as an @Input() Binds the selected values to an array so that the parent comp ...

Compiling TypeScript code with Electron

Every time I attempt to compile a TypeScript Electron project sample, I encounter the issue 'chrome' does not exist on type ProcessVersions. Despite the Electron website suggesting that including the Electron node_module should provide TypeScript ...

The HTTP request is failing to transmit cookies

Running an angular application on port 4200 and a flask python backend on port 8080 locally presented some challenges with setting cookies. To resolve this issue, I modified the /etc/hosts file to include the domain for both applications: 127.0.0.1 ...