Sequenced HTTP requests using Angular 2 and TypeScript

Within an Angular 2 form, the task at hand is to fetch the first name and last name through a http get call. This call requires a user_id, which is obtained from a previous http get call made to another endpoint.

Although there are concerns regarding similar issues with async http get calls, none of the existing solutions have proven to be truly effective in this case.

The initial call retrieves the user_id field without sending any additional parameters to the server:

/API/system/session/unusedid

This call returns the following information -->

{"user_name":"rgar003","session_id":"0635400936","is_technical_user":"false","user_id":"403"}

With the retrieved user_id (403), it's now possible to make another call to a different endpoint and retrieve the corresponding userName and lastName:

/API/identity/user/403    //403 or whatever the user_id is

This call provides the following data -->

{"job_title":"dsf","userName":"rgar003","lastname":"Garcia","firstname":"Robert"}

The objective now is to display the first name and last name within a disabled form input. Currently, only the user_id is being displayed.

The template featuring the disabled field where the name and lastmane should appear:

<div class="col-sm-5">
    <label for="petitioner">Petitioner</label>
    <input [(ngModel)]="data.petitioner" type="text" class="form-control" name="petitioner" disabled>
</div>

The component home houses a function that is responsible for loading the petitioner's user_id from the backend:

constructor(private workflowService: WorkflowService, private parametersService: UrlParametersService, private _ref: ChangeDetectorRef) {

this.formMode = parametersService.formMode;

  // origin:  /API/system/session/unusedId
  this.workflowService.loadPetitioner().subscribe(
    res => {
      this.data.petitioner= res;
    }
  );

The workflow.service class holds the aforementioned function:

constructor(private http: Http, private parametersService: UrlParametersService, private router: Router, private _configurations: ConfigurationsService) {}

public loadPetitioner(): Observable<string> {
  return this.http.get("/API/system/session/unusedId", {withCredentials: true}).map(value => value.json().user_name);
}

Various chaining methods were attempted, all of which proved unsuccessful. However, If a direct call is made to /API/identity/user/403 with the user_id hardcoded, the retrieval of the first name + last name functions as intended. Here's how:

getPetitionerFirstNamePlusLastName(): Observable<string>{
return this.http.get("/API/identity/user/403",  {withCredentials: true}).map(value =>(value.json().firstname + " " +  value.json().lastname));
}

An asynchronous issue appears to persist, despite efforts to address it by examining related problems.

Answer №1

Why not give this a shot?

this.authService.fetchUserDetails().switchMap( response => {
      let userId = response;
      return this.getUserName(userId);
}).subscribe( userName => {
      // Perform operations with the user's name
});

Don't forget to include userId as a parameter in the getUserName method

getUserName(userId:number): Observable<string>{
     return this.http.get("/API/user/profile/" + userId,  {withCredentials: true}).map(data =>(data.json().firstName + " " +  data.json().lastName));
}

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

Is it possible to add new values to a GraphQL query?

I am currently utilizing GraphQL and Typeorm in conjunction with an Oracle Database, specifically focusing on retrieving all data from a specific table. The query that is being executed is: SELECT "inventory"."id" AS "inventory_id", "inventory"."value" AS ...

Cypress - AG-Grid table: Typing command causing focus loss in Cell

Encountering a peculiar issue: I am attempting to input a value into the cell using 'type()'. My suspicion is that each letter typed causes the focus on the cell to be lost. It seems that due to this constant loss of focus and the 'type()& ...

The click event is activated following the :active selector being triggered

My Angular application features a button with a slight animation - it moves down by a few pixels when clicked on: &:active { margin: 15px 0 0 0; } The button also has a (click)="myFunction()" event listener attached to it. A common issue arises w ...

What is the process of integrating an MVC View into the template URI of a typescript component?

I am currently working on a project using MVC core and AngularJS2 with TypeScript. I recently added a new component (View located in Views\Home\Default.cshml) but I am encountering some issues. Below is the code I have tried: import { Componen ...

Using Typescript literal types as keys in an indexer is a common practice

Can we create a TypeScript literal type that acts as a string key in an indexer? type TColorKey = 'dark' | 'light'; interface ColorMap { [period: TColorKey]: Color; } But when attempting this, the following error is generated: An ...

*ngIf-else not displaying the alternate results

I am completely stuck and can't figure out why my code isn't working. Is there anyone who can help me identify the issue? I am attempting to display a "Ticket not found" message when there are no tickets to show. Despite trying to check the leng ...

Continuous HTTP Stream Observable that only transfers data without emitting any other items

I've encountered an issue while working with Angular 4 and RxJS. In my code, the Observable generated by the http.post request is not passing any data to the subsequent map() function. The POST request seems to result in an endless stream of Motion JP ...

Angular error: The function redirectToLogin in src_app_app_routing_module__WEBPACK_IMPORTED_MODULE_0__.AppRoutingModule is not defined

I'm attempting to redirect users from the homepage to the login page using home.component.ts. Within this file, I've invoked a static method called "AppRoutingModule.redirectToLogin()" that I've defined in app-routing.module.ts by importing ...

Issue with Vue plugin syntax causing component not to load

I'm facing an issue with a Vue plugin that I have. The code for the plugin is as follows: import _Vue from "vue"; import particles from "./Particles.vue"; const VueParticles = (Vue: typeof _Vue, options: unknown) => { _Vue. ...

Errors encountered when using Mongoose and TypeScript for operations involving $addToSet, $push, and $pull

I am encountering an issue with a function that subscribes a "userId" to a threadId as shown below: suscribeToThread: async (threadId: IThread["_id"], userId: IUser["_id"]) => { return await threadModel.updateOne( { _id: t ...

Tips for resolving the issue of 'defineExpose' method being undefined in Vue3

Struggling to pass a method from child to parent; unfortunately, the defineExpose() method seems to be malfunctioning. Could anyone provide guidance on what might be going wrong? For additional context, feel free to check out my previous question <scri ...

Error: Unable to access $rootScope in the http interceptor response function

I have set up an interceptor to display an ajax spinner while loading. interface IInterceptorScope extends angular.IRootScopeService { loading: number; } export class Interceptor { public static Factory($q: angular.IQService, $ro ...

ArrangementGrid utilizing ngFor directive for rows and columns

Hi there, I am new to using Nativescript and I have encountered an issue with ngFor. Specifically, I am working with a GridLayout that contains a StackLayout inside of it and I need to set dynamic col and row values within the StackLayout. Can anyone pro ...

Converting Promises to Observables

Struggling with the syntax as I delve into learning Angular, I need to transform a promise into an Observable. Let me share what I've encountered: In the function getCountries (subscribed by another utility), there is a call required to fetch a list ...

Issue with Angular 2 Bootstrap dropdown functionality (ngx-bootstrap/ng2-bootstrap)

I am having trouble getting Angular Bootstrap dropdowns to function properly in certain areas of my application. Strangely, they work fine in one part but not in others. I have checked that I am importing with BsDropdownModule.forRoot() as required, just l ...

How to refresh an array in Angular 4 after inserting a new element using splice method?

I have a Angular list displayed in a table, and I need to insert an element at a specific position. I have tried using the following code: array.splice(index, 0, element); While everything seems fine in the console with the element being added at the corr ...

Adding cache to Observable in mat-autocomplete can improve performance by reducing redundant API calls

I have successfully implemented a mat-autocomplete feature. However, I am facing an issue where the Http call is triggered with every keyup event, such as 'r', 'ra', 'ram', 'rame', 'ramesh'. This frequent u ...

leveraging jQuery across an Angular 2 application as a global tool

I'm currently exploring ways to incorporate jQuery globally throughout my angular 2 application. The only comprehensive resource I've come across so far is this Stack Overflow answer. However, despite my efforts, I haven't been able to make ...

Challenges in conducting asynchronous tests for Angular2 due to setTimeout complications

Using Angular2.0.1, I encountered an issue while trying to write unit tests for an angular component that involved async tasks. This is a common scenario and even the latest testing examples from Angular include async tests (see here). My test kept failin ...

Having trouble reaching the angular app when using nginx and istio

I am currently working on setting up an Istio service mesh for a project that involves .NET Core services and Angular 6 as the front end. Interestingly, when I deploy the application with built-in Docker applications, everything runs smoothly. For exampl ...