Angular 6 - Failure to Trigger Chained API Requests

I am currently developing an authentication system that operates in two parts.

Firstly, I need to make a call with the username and password. If the credentials are valid, a code is returned.

This code must then be checked for validity, and if it passes the check, the user is authenticated.

The following function is used to obtain the code:

  requestAuthCode(request: models.AuthenticationRequest): Observable<any> {
    return this.httpClient
      .get<any>(environment.auth.authorize, {
        headers: headers,
        params: params
      })
      .pipe(
        tap(val => this.authenticate(val.code)),
        catchError(error => this.handleError(error))
      );
  }

This function verifies the code's authenticity and authenticates the user:

  authenticate(code: string): Observable<any> {
    return this.httpClient
      .post<models.AuthenticationTokenResponse>(
        environment.auth.token,
        null,
        {
          headers: headers,
          params: params
        }
      )
      .pipe(
        tap(data => this.setSession(data)),
        catchError(error => this.handleError(error))
      );
  }

Objective

If requestAuthCode receives a code in its response, I want it to trigger the authenticate function. Otherwise, it should return an error.

However, when I use

this.authService.requestAuthCode(request)
        .subscribe(
          data =>  {
            console.log(data);
          }

I only retrieve the response data from my requestAuthCode function and not from the subsequent authenticate function call. Additionally, it appears that the authenticate function is not being executed.

Is there a way to ensure that requestAuthCode triggers the authenticate function and sends back the data to my component?

Answer №1

Instead of

  tap(val => this.authenticate(val.code)),

consider trying

 switchMap(val => this.authenticate(val.code)),

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

Eliminate Elements from Array - Angular Four

I am currently developing a basic to-do app using Angular4. The setup of the app is structured as follows: Form Component: Responsible for adding items to the to-do list Item Component: Represents individual to-do items App Component: Contains a *ngFo ...

Discover the simplicity of incorporating pagination into an HTML table with Angular Material

My goal is to implement pagination on my webpage, displaying 3 rows per page and enabling navigation through pages using Angular Material pagination. In usersComponent.ts, I retrieved data from an API: import { Component, OnInit, ViewChild } from '@an ...

Successfully integrating the twit npm package into meteor.js

I'm currently facing some challenges in fetching tweets using the twit npm package and meteor. Despite installing meteorhacks:npm and http as dependencies, I'm still unable to make it work. Below is my code: /* server/lib/twitter-api.js */ Me ...

Restricting a generic parameter to a combination type in Typescript

Is there a method in Typescript to restrict a generic parameter to only accept a union type? To clarify my question, I wish that T extends UnionType would serve this purpose: function doSomethingWithUnion<T extends UnionType>(val: T) {} doSomethingW ...

What is the best way to utilize the fresh Sanitizer API in Typescript?

Everything seems to be working well on Codepen, even without using window. It's surprising because I'm used to having to use window.x if ( 'Sanitizer' in window ) { console.log( 'sani', 'Sanitizer' in window ); } ...

Is it possible to retrieve a single attribute from a parent object using the Fast JSON API within Rails?

I am in the process of developing a travel application that utilizes a backend Rails API. To serialize my data, I have chosen to implement the Fast JSON API. Within my app, there exists a collection of countries, each containing numerous cities and attract ...

Side navigation in Angular is not causing the main content to shrink

In my layout, I have a container that includes two sidenavs and multiple tables in between them. When I toggle the left sidenav, instead of the expected behavior where the content shrinks to accommodate the sidenav, the tables get pushed to the right as if ...

A secure method for converting a key and a corresponding value into an object containing only that specific key/value pair

I need to implement a function called valueToObject that takes a key and a value as arguments and returns an object with that key and value pair, like this: valueToObject('myKey', 3); // should yield {myKey: 3} I attempted to write the followin ...

Determined the resulting data type from the given input

If there is a function structured like this: static async getPets({ petType, inverseOrder }: { petType: string; inverseOrder?: boolean }) { const [petsFound, totalFound] = await getPetsByType(petType, inverseOrder); return { [petType]: pets ...

Angular's Motion Module

Incorporating Angular-5 into my project has introduced a plethora of animations on various pages. While the utilization of jQuery provides a straightforward approach for adding and removing classes to DOM elements, it is frequently advised against using jQ ...

SwitchMap in Typescript allows you to switch to a

In my TypeScript code, I have implemented multiple interfaces, components, and a key/interface map. interface FooProps { 'keyInFoo': string } const Foo = (props: FooProps) => {} interface BarProps { 'keyInBar': string } cons ...

TS2322: Subclass missing property, yet it still exists

In my project, I have defined two Angular 4 component classes. The first class, referred to as the superclass: export class SectionComponent implements OnInit { slides: SlideComponent[]; constructor() { } ngOnInit() { } } And then there&apo ...

Inquiring about developing an API with Django - seeking guidance

Hey everyone! I've been given a test that requires me to create an API, but I'm not too familiar with how to do that. The test prompt is as follows: "To identify debtors, track credit recovery statuses, and gather additional information, ...

Conceal certain components when a user is authenticated

Below is the content of my app.component.html: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class='container'> <ul class="nav navbar-nav"> <li class='nav-item'> <a clas ...

Automatically open the previously viewed page when starting up the Chrome extension

As I embark on creating my very first Chrome extension, I've encountered a roadblock in the form of a "session restore" issue. Early on in development, it became apparent that when a user logged into my extension and closed the popup, they would have ...

Problem of Restricting Array to Single Element at Once

I seem to be facing an issue with a seemingly straightforward function that creates an array - and I'm unable to pinpoint the root cause of the problem. It's probably something simple, but for some reason, it eludes me. Here is the function in q ...

What is the best Google OAuth Playground API to utilize for generating a token that includes the user's name, profile picture, and email address?

I recently came across a helpful tool from Google at https://developers.google.com/oauthplayground/. I am currently practicing authentication for an API with Node.js and Passport.js. I am looking to obtain a token with the user's email and profile pho ...

Hiding the rail mode on mobile for Angular Material SideNav

I've been utilizing the incredible Rail directive for the Angular Material SideNav component developed by Jordan Hall. You can find more information about it at https://github.com/Jordan-Hall/angular-material-rail-drawer-plugin This directive introdu ...

Updating our project from Angular version 17 to version 18

Seeking guidance on updating a project from Angular v17 to v18 as there seems to be a lack of documentation on version updates available on the official angular.dev website. Any assistance or guidance on this matter would be greatly appreciated. Thank yo ...

Angular 5 offers the ability to incorporate dynamic checkbox input into your application

Here is my code snippet: <input [type]="'checkbox'" [(ngModel)]="inputValue"> <p>Value: {{ inputValue }}</p> I'm puzzled as to why the value in inputValue remains unchanged. Can anyone shed light on this? I am unable to ...