Transfer the output of a function in a service to a different function

I have a unique service that connects to 2 different API endpoints. The first endpoint retrieves the user's id along with a JWT token:

@Injectable()
 export class UserService {

  appLogin = 'http://url.for.the.login.api';
  //returns id and token
  userData = 'http://url.for.the.user_info.api';
  //returns user info

  constructor(private http: HttpClient) { }

  getAll() {
    return this.http.get<User[]>(`${this.appLogin}`);
    //retrieves id and token, can be displayed in the template like this {{currentUser.id}}
  }

 }

Next, I require another method that utilizes the id and token retrieved from the first request to make a subsequent GET request. The URL for this request should look something like this:

http://url.for.the.user_info.api/userID?token=token_string

Here is the current implementation for this scenario:

 getInfo(id: number, token: string) {

    let userData = this.http.get<User[]>(`${this.appLogin}` + id + '?token=' + token);
    return this.http.get<User[]>(`${userData}`);
}

However, I am encountering challenges with this setup. Any assistance provided would be greatly appreciated.

Answer №1

To implement the desired functionality, utilize the switchMap function in the following manner:

return this.http.get<User[]>(`${this.appLogin}` + id + '?token=' + token)
    .pipe(switchMap(userData) => this.http.get<User[]>(`${userData}`))

If necessary, make sure to include the appropriate import statement for switchMap:

import { switchMap } from 'rxjs/operators';

By integrating the original request with switchMap, a new Observable can be generated.

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

Combine multiple arrays containing observables into a unified array

I am facing the challenge of flattening a nested Observable into a single observable array. The Observable looks like this: Observable<Observable<any[]>[]> values; The inner arrays have the following structure: [ {id: 0, name: 'a'} ...

d3 split bar chart with a horizontal layout

https://i.sstatic.net/P6qck.png I am interested in creating a split difference bar chart using d3 similar to the image provided. I have two input arrays - one for y-axis labels and one for data as shown below: data = [[35,90], [60,45], [80,90], [95,90]] m ...

How to handle an already initialised array in Angular?

I came across an interesting demo on exporting data to Excel using Angular 12. The demo can be found at the following link: This particular example utilizes an array within the component TypeScript file. import { Component } from '@angular/core' ...

Angular - passing information to a nested component

Within my application, I have a main component along with three sub-components. I am passing data to these three sub-components and using setTimeout to manage the timing of the data being sent. The first sub-component displays for 5000 milliseconds. The ...

Navigating between pages has become challenging due to issues with the navbar, sidebar,

I successfully developed 4 Angular components: 1st component: menu 2nd component: header 3rd component: home 4th component: login The menu component features a sidebar/navbar created using Material UI. The login component consists of the login page. Howe ...

The useAutocomplete function in Material-UI fails to consider the disabled

Currently, I am working on developing my own Autocomplete component by utilizing the useAutocomplete hook from the mui/base package. Most parts of the implementation are functioning correctly, except for the disabled option. My expectation is that the com ...

What steps are involved in developing an Angular library wrapper for a pre-existing Javascript library?

Imagine having a vanilla Javascript library that is commonly used on websites without any frameworks. How can you create an Angular library that can be easily installed via npm to seamlessly integrate the library into an Angular application? The process o ...

Having trouble accessing a variable from the material theme in Angular 7

Currently, I am working with Angular 7.0.3 and endeavoring to establish an scss variable with the primary color of my material theme. // src/styles/_variables.scss @import "~@angular/material/theming"; @include mat-core(); $app-primary: mat-palette($mat-i ...

Unable to execute an Angular 2 application within Visual Studio 2015

I encountered an error while trying to set up an environment on VS 2015 with Angular2. Whenever I run the command "npm start," I receive the following error message. I attempted using "npm cache clean --force" before running "npm start," but the error pers ...

Prisma does not automatically update interfaces

I am currently working on a Nest.js project with Prisma as my ORM. However, I have encountered an issue that needs to be addressed: My User model is quite simple: model User { id String @id @default(uuid()) @db.Uuid firstName ...

The combination of the video tag within an SVG element is causing a strange error

I'm encountering an issue while attempting to implement the code provided in this particular answer. Despite following the code, I am receiving an error in the console log instead: Here's the Code Snippet: <svg version="1.1" class="center-bl ...

A guide to implementing "Intl.DateTimeFormat" within a Next.js React component

I have a component that is being rendered on the server, making "Intl.DateTimeFormat" accessible. What is the proper way to use "Intl.DateTimeFormat" in a Next.js React component? The error message I am encountering is: Error: There was an error while hy ...

Filtering an Observable object in Angular

Looking for assistance in filtering the JSON data object to only display trams heading towards a designated station. Here is my current code: import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http&apos ...

Angular 11 is indicating that the type 'File | null' cannot be assigned to the type 'File'

Hey there, I'm currently diving into Angular and I'm working on an Angular 11 project. My task involves uploading a CSV file, extracting the records on the client side, and saving them in a database through ASP.NET Web API. I followed a tutorial ...

The TypeScript declaration for `gapi.client.storage` is being overlooked

When I call gapi.client.storage.buckets.list(), TypeScript gives me an error saying "Property 'storage' does not exist on type 'typeof client'." This issue is occurring within a Vue.js application where I am utilizing the GAPI library. ...

Application of Criteria for Zod Depending on Data Stored in Array Field

I am currently working on an Express route that requires validation of the request body using Zod. The challenge arises when I need to conditionally require certain fields based on the values in the "channels" field, which is an array of enums. While my cu ...

Animating Angular ng-template on open/close state status

I am looking to add animation when the status of my ng-template changes, but I am unable to find any information about this component... This is the code in my report.component.html <ngb-accordion (click)="arrowRotation(i)" (panelChange)="isOpen($even ...

An error was encountered in the rxjs-compat module at operator/shareReplay.d.ts line 2, character 10: TypeScript error TS2305

Currently, I am in the process of upgrading a basic Angular skeleton application from version 5 to version 6. However, I have encountered an issue while attempting to run the application: ERROR in node_modules/rxjs-compat/operator/shareReplay.d.ts(2,10): ...

Creating dynamic data-automation-ids for each option may be achieved by utilizing a method that

I am a newcomer to Angular and have written some code that includes two dropdown menus using simple HTML select and option tags. While these menus are functioning correctly, the QA team is having trouble testing them. How can I dynamically add a data-autom ...

What is the method for retrieving the second type of property from an array of objects?

I have a collection of objects that map other objects with unique identifiers (id) and names (name). My goal is to retrieve the name corresponding to a specific id. Here is my initial approach: const obj = { foo: { id: 1, name: 'one' }, ...