How to Link an Observable Array to Another in Angular 2

In my Angular 2 project, I am trying to chain multiple HTTP calls together. Initially, I retrieve an array of environments with one call. For each environment, I want to make another call and create objects like

firstObject[{name:"name",secondObject[stuff,stuff2],name:"name2",secondObject[stuff,stuff2]]

However, when I attempt to use a for loop in the array, the lazy nature of the subscribe function makes it difficult to iterate through each object. It seems that the same index is being used on each of the second subscribes. Below is the code output. Any assistance would be greatly appreciated.

getEnvironments(app:string){
this.loading = true;
console.log("calling get Environments")
 this._appModelService.getEnvironments(app).subscribe(val => 
  {this.environments = val;
    for(var i = 0; i < this.environments.length;++i){
      console.log("Environment name =       "+this.environments[i].EnvName);
         this._appModelService.getAppTypes(app,this.environments[i].EnvName)
      .subscribe(typeVal => 
      {
        console.log("Subscribing to i = "+i);
        console.log(typeVal);
      }

      )
    }

    this.loading = false;
  },

  err => {
  console.log("Something went wrong in get apps");                              // Log errors if any
  console.log(err);
  this.loading = false;

});

  }

Output Below

calling get Environments
app-model.component.ts:93 Environment name = CRT       
app-model.component.ts:93 Environment name = DRP       
app-model.component.ts:93 Environment name = IFT       
app-model.component.ts:93 Environment name = PRD       
app-model.component.ts:93 Environment name = PRE       
app-model.component.ts:93 Environment name = TRN       
app-model.component.ts:97 Subscribing to i = 6
app-model.component.ts:98 [Object, Object, Object]
app-model.component.ts:97 Subscribing to i = 6
app-model.component.ts:98 [Object, Object, Object]
app-model.component.ts:97 Subscribing to i = 6
app-model.component.ts:98 [Object, Object, Object]
app-model.component.ts:97 Subscribing to i = 6
app-model.component.ts:98 [Object, Object, Object]
app-model.component.ts:97 Subscribing to i = 6
app-model.component.ts:98 [Object, Object, Object]
app-model.component.ts:97 Subscribing to i = 6
app-model.component.ts:98 [Object, Object]

Edit The output of my first call should look like this<

[ { EnvName: 'CRT       ' },
{ EnvName: 'DRP       ' },
{ EnvName: 'IFT       ' },
{ EnvName: 'PRD       ' },
{ EnvName: 'PRE       ' },
{ EnvName: 'TRN       ' },

And the output of the second Call will be

[ { ServerTypeName: 'App       ' },
{ ServerTypeName: 'Oracle    ' },
{ ServerTypeName: 'Weblogic  ' } ]

I aim to combine these into a nested object.

Answer №1

Could you provide us with the code for the service?

It is recommended to chain the calls like this:

    this._appModelService.getEnvironments(app).subscribe(
        res => {
            // process data returned from response
            // perform additional action after successful response
            this._appModelService.someOtherCall().subscribe()
        },
        err {},
        ()
    )

If you need to manipulate the same data or combine data in the service, you should consider using flatMap to chain various http requests.

Answer №2

In case anyone is still searching for a solution to the identical issue mentioned earlier, consider utilizing a forkJoin method.

fetchEnvironments(application:string): Observable<any> {
  this._applicationModelService.fetchEnvironments(application)
  .pipe(
    //transforming fetchEnvironments into...
    mergeMap((environments:any[]) => {
      //a combination of multiple obtainApplicationTypes observables
      return forkJoin(
        environments.map(env => this._applicationModelService.obtainApplicationTypes(application, env.EnvName).pipe(
          map(typeValue => {
            return {/* an alternative approach to merging `env` and `typeValue` */}
          })
        ))
      ).pipe(
        map((typeValues:any[]) => { //final touch to compile response object
          return {/* a method to consolidate all the responses */}
        })
      )
    })
  )
}

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

The ng-bootstrap package is not fully compatible with Bootstrap 4 Alpha 6, particularly when it comes to collapsible elements such as forms

Just a heads up for everyone, the current version of ng-bootstrap is not compatible with the latest release of Bootstrap (Alpha 6). This includes collapsing elements like collapses, dropdowns, navs, etc. I haven't figured out how to make the package ...

Guide to setting a generic key restriction on a function parameter

Today, I decided to have some coding fun and try creating a generic pushUnique function. This function is designed to check if a new object being added to an array is unique based on a key, and then push it if it meets the criteria. At this point, all I h ...

Determine whether a many-to-many relationship involves a specific entity

I am currently working on developing an API for managing surveys. One challenge I'm facing is determining whether a specific user has moderation privileges for a particular survey. A many-to-many relationship has been set up between the two entities. ...

Oops! An issue occurred: [RunScriptError]: Running "C:Windowssystem32cmd.exe /d /s /c electron-builder install-app-deps" resulted in an error with exit code 1

query: https://github.com/electron/electron/issues/29273 I am having trouble with the installation package as it keeps failing and showing errors. Any tips or suggestions would be highly appreciated. Thank you! ...

Change the values of every element in an array

Looking to update the values of every item in an array list? if (country.hostel) { country.hostel.forEach(function (hostel, index) { hostel.room.forEach(function (room, index) { room = {code:{value: BOOKED}}; ...

Creating a task management application using Vue 3 Composition API and Typescript with reactivity

I am in the process of creating a simple todo list application using Vue 3 Composition API and TypeScript. Initially, I set up the function for my component to utilize the ref method to manage the reactivity of user input inserted into the listItems array. ...

The module has defined the component locally, however, it has not been made available for

I have developed a collaborative module where I declared and exported the necessary component for use in other modules. import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { DateslideCompone ...

"Looking to personalize marker clusters using ngx-leaflet.markercluster? Let's explore some ways to customize

I am currently struggling to implement custom cluster options in ngx-leaflet. My goal is simply to change all marker clusters to display the word "hello". The demo available at https://github.com/Asymmetrik/ngx-leaflet-markercluster/tree/master/src/demo/a ...

What could be causing my NodeJS Backend to not retrieve the data properly?

For a current project, I am tasked with building a mobile application using Flutter for the frontend and NodeJS for the backend. To facilitate this, I have acquired a VPS from OVHcloud running Ubuntu 20.04. Following various tutorials, I set up a server as ...

Unable to assign to 'options' as it is not recognized as a valid property of 'p-multiSelect'

I am currently in the process of incorporating the datatable filter from primeng into my project. Here is the code snippet I have written: <p-column field="time" header="Time" [filter]="true" filterPlaceholder="&#xf0b0;"> <ng-template pTe ...

Creating anchor links with #id that function correctly in an Angular project can sometimes be challenging

My backend markdown compiler generates the HTML content, and I need Angular to retrieve data from the server, dynamically render the content, and display it. An example of the mock markdown content is: <h1 id="test1">Test 1<a href="#test1" title ...

Performing an Axios POST request in a React Native and React app using JSON.stringify and Blob functionality

I am currently developing an application where I have encountered an issue when calling an API endpoint in react native. Interestingly, the web app (built with React) does not encounter any errors. Here is the code for the web app using React with TypeScri ...

Switching out a traditional class component with a functional component within a hook to deduce properties from T

One challenge is to subtract props from T within the withHookFn function using a function instead of a class as successfully done in the withHook function. The code contains comments explaining this issue. Dive into the code for more insights. import Reac ...

Error in Typescript: The identifier 'Proxy' is unknown

I'm trying to create a new variable using the Proxy type from the ES6 specification: myProxy: Proxy; However, I'm encountering the following error: Cannot find name 'Proxy'. Can anyone point me in the right direction to resolve th ...

Managing clearing values/strings for different input types like text/password upon form submission in Angular2

Here is a code snippet for an HTML form: <div> <form class="form-horizontal" role="form" (ngSubmit)="createUser(Username.value, Password.value)"> <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6"> <input type="text" class=" ...

Encountering the error "Missing property '$$typeof' when trying to extend next/link in Next.js using TypeScript"

I have the following code snippet in my project: import NextLink from 'next/link' import ExternalLink from './External' type PropsType = typeof NextLink & { href: string children: React.ReactNode } export default function Link ...

What steps can be taken to properly set up routing in Angular 4 in a way that organizes feature-modules routes as children in the

Organizational layout of projects: /app app.module.ts app.routing.ts : : /dashboardModule /manage-productModule manage-product.module.ts manage-product.routing.ts Within 'app.routing.ts' [ { path : '&a ...

Angular: Understanding the intricacies of HTTP calls in ngOnInit versus click events (potentially related to caching mechanisms)

Within my Angular application, I have a basic service configured to communicate with the server. The service has been injected into a component. Interestingly, when I directly call one of its methods inside the ngOnInit() method of the component, everythin ...

Guide on inserting a template into mat-stepper

My goal is to achieve the following: <ng-template #content> <mat-step>step 1</mat-step> <mat-step>step 2</mat-step> </ng-template> <mat-horizontal-stepper> <ng-container *ngTemplateOutlet="content">&l ...

Issue with sending headers in HttpClient.post method in Angular 8

I have successfully implemented the following code: this.http.post (TGT_IP,body, {responseType: 'arraybuffer'}).subscribe( (val) => { console.log("POST call successful value returned in body", val); ...