The redirection code is not being executed when calling .pipe() before .subscribe()

My AuthService has the following methods:

signUp = (data: SignUp): Observable<AuthResponseData> => {
  const endpoint = `${env.authBaseUrl}:signUp?key=${env.firebaseKey}`;
  return this._signInOrSignUp(endpoint, data);
};

signIn = (data: SignIn): Observable<AuthResponseData> => {
  const endpoint = `${env.authBaseUrl}:signInWithPassword?key=${env.firebaseKey}`;
  return this._signInOrSignUp(endpoint, data);
};

private _signInOrSignUp = (endpoint: string, data: SignIn | SignUp): Observable<AuthResponseData> => {
  return this.http.post<AuthResponseData>(endpoint, {
    ...data,
    returnSecureToken: true
  }).pipe(
    catchError(error => this._throwError(error)),
    tap(response => this._createAndEmitUserSubject(response)),
  );
}

private _throwError = error => {
  const errorMessage = error.error.error.message;
  return throwError(errorMessage);
};

private _createAndEmitUserSubject = (response: AuthResponseData) => {
  const expirationDate = new Date(new Date().getTime() + +response.expiresIn * 1000);
  const user = new User(
    response.idToken,
    response.email,
    response.idToken,
    expirationDate
  );

  localStorage.setItem("user", JSON.stringify(user));
  this.user$.next(user);
};

In my sign-in and sign-up components, I make use of these methods as shown below:

submit = (): void => {
  if (this.loginForm.invalid) {
    return;
  }

  this.authService
    .signIn(this.loginForm.value)
    .subscribe({
      next: () => this.router.navigate(["/recipes"]),
      error: error => this.error = error
    });
};

However, the code within next is not executed. It works when I remove .pipe(), but I was hoping to avoid using it in multiple places.

Answer №1

It seems that the function this._throwError is not actually throwing an error as expected. If it were, the function next would not be able to be called subsequently. It is likely that you are not using the throw statement to throw an error within the function, but rather returning a value that is then passed into next

Answer №2

After removing the line this.user$.next(user), I discovered that it was unnecessary all along. However, I am curious as to why it was blocking the flow.

private _createAndEmitUserSubject = (response: AuthResponseData) => {
  // ...

  localStorage.setItem("user", JSON.stringify(user));
};

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

TabContainer - streamline your selection process with inline tabs

I am currently working on a GUI that includes a TabContainer with two tabs, each containing a different datagrid. I initially created the tabcontainer divs and datagrids declaratively in HTML for simplicity, but I am open to changing this approach if it wo ...

Posting data from an Angular 2 frontend to an Express server: A step-by-step

Seeking guidance as a beginner trying to understand the process of sending contact form data from Angular 2 to a Node/Express server. Currently, I have Angular 2 hosted on localhost:4200 and the express server running on localhost:3000. However, when attem ...

The attempt to convert an array into an array of objects using the map function was

var array = ["x","y","z"] array.map(object => {object.key: object}) I thought array would transform into [{key:"x"},{key:"y"},{key:"z"}] but I encountered an error at object.key in my map function. Where did I go wrong? ...

The Angular component refuses to open

Having some trouble with my navbar containing different components that should open upon selection. The profile component is opening correctly, but the "My favorites" button isn't displaying anything from that component. Here's the code snippet ...

Attempted to display a Google Map within a lightbox, but encountered difficulties in getting it to

I've copied and pasted my code below. It may contain references to Google or Lightbox being undefined, but I'm unsure how to integrate them into the code provided. My goal is to display a Google map within a Lightbox popup, but so far I have been ...

Is there a way for me to receive numerical values instead of NaN?

I'm currently facing a challenge in creating a Fibonacci number generator and I've hit a roadblock. It seems like I have a solution, but the appearance of NaN's is causing me some trouble. function fibonacciGenerator (n) { var output = [ ...

Working with three.js: Implementing an external texture in a glTF file

In my quest to apply a texture file to a 3D model using three.js, I've hit a roadblock. Despite days of research and numerous attempts, I just can't seem to get it right. Here is the method I've been using to set the current object in the sc ...

Performing an AJAX call with JQuery when clicking on multiple anchor elements

I have a set of anchor tags created dynamically through PHP from a database query, like the following: <a href="#" id="reply_doc" data-doc_value="1"></a> <a href="#" id="reply_doc" data-doc_value="2"></a> <a href="#" id="reply_d ...

Ways to identify and differentiate user clicks on various buttons

I have generated 3 different plan options from an array of objects retrieved from the backend. Depending on whether the plan is cheaper, the user's subscription, the corresponding button will display "downgrade", more expensive, the button will show ...

How can Typescript help enhance the readability of optional React prop types?

When working with React, it is common practice to use null to indicate that a prop is optional: function Foo({ count = null }) {} The TypeScript type for this scenario would be: function Foo({ count = null }: { count: number | null }): ReactElement {} Wh ...

fetch the image data from the clipboard

Hey there! Is it possible to use JavaScript to retrieve an image from the system clipboard (Windows/Mac) and paste it into a website? ...

Is there a way for me to input only the value and have TypeScript automatically determine the key of an object?

My challenge lies in having an object with string keys, but I do not want them to remain as strings. Instead, I desire the keys to be the exact values of the object. This means that I must input the value of the object accordingly to meet certain criteria. ...

In the middleware, the request body is empty, but in the controller, it contains content

Below is my server.js file: import express from "express"; import mongoose from "mongoose"; import productRouter from "./routers/productRouter.js"; import dotenv from "dotenv"; dotenv.config(); const app = expres ...

Explore various locations and conceal different divs by clicking

Can someone help me figure out how to hide the placeholders when the focus changes in a form? Here is the code snippet that illustrates my problem. Your assistance is greatly appreciated, João var inputs = Array.prototype.slice.call(document.querySele ...

What is the process for incorporating a standalone custom directive into a non-standalone component in Angular?

Implementing a custom directive in a non-standalone component I have developed a custom structural directive and I would like to use it across multiple components. Everything functions as expected when it is not standalone, but encountering an error when ...

Error loading ngsw-worker.js in Angular 7

Issue An app that utilizes a Service Worker is experiencing problems. The app was recently upgraded from Angular 6.1 to version 7. Upon uploading the updated files to the server, an error message is displayed: https://i.sstatic.net/B7uPf.png Error Det ...

The website functions properly in Chrome, but encounters issues in IE

Currently working on validating some JavaScript code. Chrome seems to be handling it well, but as expected, IE is causing some issues. Take a look at the code below: function validateData(a,id){ var inputs = document.getElementsByName('attname[] ...

Ways to utilize two distinct XPATH values for a single key

When dealing with Xpath for the same object in two different portals, the paths can be: //*[@id="abc"]/fieldset/div/div/div[1]/label //*[@id="xyz"]/fieldset/div[1]/fieldset/div/div/div[1]/label In order to use both values in the same key and have Seleni ...

Error: The value property is undefined and cannot be read at the HTMLButtonElement

I'm currently working on a project where I need to display a dropdown menu of buttons using Pug in order to render an HTML page. To achieve this, I am using the getElementsByClassName('dropdown-item') method to retrieve all the buttons in an ...

Tips on utilizing Selenium with Java to locate and interact with elements on an Angular web application

I'm facing challenges with automating an Angular web app. Despite trying simple code, it still isn't working. Here's an example of my code: @BeforeClass public void setUp() { ChromeOptions options = new ChromeOptions(); ...