Angular: The behavior of observables is altered when a pipe and tab are used together

Having an issue with Angular 10 where the behavior of my observable changes based on whether I use a pipe or not. Here are the relevant snippets from my code.

auth.service.ts

...
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
...
register(email: string, password: string): Observable<RegistrationResponse> {
    return this.http.post<RegistrationResponse>(
      `${environment.API_URL}/users/register`,
      { email, password }).pipe(tap<RegistrationResponse>({
        next: (data) => {
          console.log('success - tap');
          if (data.jwt !== undefined) {
            this.setSession(data.jwt);
          }
        },
        error: () => {
          console.log('error - tap');
        }
      })
    );
}
...

auth.component.ts

...
this.authService.register(this.email, this.password).subscribe({
    next: (_) => {
      console.log('success');
      this.router.navigate(['/']);
    },
    error: (error) => {
      console.log('error');
      this.error = error.error || 'Error';
      this.loading = false;
    }
});
...

When there is an error response, the expected output is:

error - tap
error

But upon successful request, I get:

success - tap
error                 <--- unexpected

=> Can anyone explain this behavior and what am I missing?


Additionally, removing the tap pipe results in the completion handler being called as expected.
register(email: string, password: string): Observable<RegistrationResponse> {
    return this.http.post<RegistrationResponse>(
      `${environment.API_URL}/users/register`,
      { email, password })/*.pipe(tap<RegistrationResponse>({
        next: (data) => {
          console.log('success - tap');
          if (data.jwt !== undefined) {
            this.setSession(data.jwt);
          }
        },
        error: () => {
          console.log('error - tap');
        }
      })
    );*/
}

Output:

success

Answer №1

If you encounter an issue in your tap next function, it may be due to an error being thrown (make sure to review this.setSession(data.jwt)). Errors that occur within operators are captured and reported as error notifications by RxJS. Therefore, if an error occurs in the upstream section of your pipe, the error callback in the subscribe function will be triggered.

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

Issue with typescript in Material-UI Next

I encountered an error while trying to integrate material-ui-next component into a default VS2017 react-redux template. The error message reads as follows: ERROR in [at-loader] ./node_modules/material-ui/BottomNavigation/BottomNavigationButton.d.ts:6:74 T ...

What is the best way to increase the height of an image beyond the limits of its container, causing it to overlap with other elements

My challenge involves creating a horizontal scrolling list of movie posters. I want the posters to grow in size when hovered over, expanding outside of their container and overlapping other elements. I attempted to use 'position: absolute' on the ...

Automatically export as a namespace in a declaration file

I have a compact TypeScript library that is exported as UMD, and I generate the *.d.ts file automatically by setting "declaration": true in my tsconfig. The exported file contains: export class Blue { alert(): void { console.log('alerte ...

What is the best way to showcase a diverse list with varying templates using Angular?

Looking to showcase a variety of items sourced from a service, each potentially belonging to different types. I am in search of a way to dynamically display distinct templates for each item based on its value or type. Is there a functionality that allows ...

Trouble detecting change event in Angular 2 form with <ng-datepicker> component

Hello, I am currently working with the code provided below and I need the date selection to trigger a specific function. However, I am unsure which function to use in this case. I have tested several options such as (dateSelect), (onDateChange), (selecte ...

Grouping Rows in Angular Material's mat-table

Setting aside the libraries that offer row grouping functionality for their specific tables, I am exploring ways to incorporate this feature into an Angular Material 2 mat-table, which does not natively support it. Below is a sample object structure to po ...

The parent component needs to remain active while the Angular Material dialog is open

Recently, I added angular material dialog to my project and successfully made it draggable. However, a new requirement has arisen where the parent component should remain active when the dialog is opened. Does anyone have any suggestions on how to accomp ...

What is the best way to test a function that returns a JSX element in a unit test

I created a function that takes in a parameter and returns a JSX.Element //title.tsx export const getTitle = (pageTitle: string) => { return <title> {pageTitle} </title>; } This is how I am currently testing it: describe('Title c ...

What is the best way to sort through custom components within children in Solid JS?

I have been working on developing a scene switcher for my personal application, and I thought of creating a custom component called SceneSwitcher. Inside this component, I plan to add various scenes that can be rendered. Here's an example: <SceneSw ...

Is it possible for TypeScript to verify key-value pair validity during compile time?

In my quest to efficiently cross reference field IDs with field definitions and validate them, I have encountered a common issue where string mismatches occur easily. Is there a method to establish a secure 1:1 mapping between dictionary types and their ke ...

Retrieve the text content from a component using ContentChild, rather than accessing another instance of a component

Is there a way to access the text within the tags of a component? <my-custom-component>THIS TEXT</my-custom-component> In a template, using ng-content is an option, or within the component definition as shown in these examples. However, my go ...

The IE browser is showing a blank page when I try to open my Angular 8 application

Even after incorporating all the necessary polyfills and making updates to the browserlist file and tsconfig file, I am still unable to identify a solution. Any assistance would be greatly appreciated. ...

Switching "this" keyword from jQuery to TypeScript

A piece of code is functioning properly for me. Now, I aim to incorporate this code into a TypeScript application. While I prefer to continue using jQuery, I am unsure how to adjust the use of this to meet TypeScript requirements. if ($(this).width() < ...

Leverage one Injectable service within another Injectable service in Angular 5

I am facing difficulties in utilizing an Injectable service within another Injectable service in Angular 5. Below is my crudService.ts file: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; ...

Interceptors in Angular 8 TypeScript prevent setting Headers until the token is stored in local storage

Whenever I attempt to log in, the interceptors fail to set the header of the request because it runs before the .pipe() block of service. As a result, currentUser in interceptors is always null. ///////////////////////////////////////////////////////////// ...

Is it more efficient to define a variable or call a method from an object?

Which approach is more effective and why? Option 1: Declaring a variable exampleFunction(requestData: Object) { const username = requestData.username; doSomething(username); } Option 2: Accessing the object property directly exampleFunction(reques ...

Leveraging TypeScript to Access Parameters in React Router

Currently, I am delving into the realm of TypeScript usage in my React projects and I have encountered a stumbling block when it comes to implementing React Router's useParams() feature. My import statement looks like this: import { useParams } from ...

Can [] be considered a valid type in Typescript language?

I've come across this function: function stringToArray(s: string|[]): [] { return typeof s === 'string' ? JSON.parse(s.replace(/'/g, '"')) : s; } This function is functioning as expected without any type warnings. Bu ...

Priority of Search Results in Ionic Search Bar

I have an array of items that I'll refer to as fruitArray. fruitArray = ['Orange', 'Banana', 'Pear', 'Tomato', 'Grape', 'Apple', 'Cherries', 'Cranberries', 'Raspberr ...

Discovering the power of Angular 2 with ngrx while putting my Reducer to the

Within my Reducer file: case PumpActionTypes.EnterLocalMode: return commandOne.upsertOne( {id: action.payload.id, changes: { local: false }}, state ); When testing, I aim to verify that the local property is indeed modified to false. My curr ...