Patience is key when handling multiple Observables in Angular 5

Having recently started working with Angular and TypeScript, my question may seem a bit off. I'm currently using Visual Studio Code along with Angular 5 (ng-version="5.2.11").

I am faced with the challenge of waiting for my API call to finish and return its result without having to wrap everything in a huge ".subscribe" block. Here is what I have:

exampleMethod(): SettingsClass {
const myComplexObject: SettingsClass = {
  field1: predefined.field1,
  field2: predefined.field2,
  field3: isComplexCalculationsNecessary ? this.CallApi_1(predefined.paramForField3) : predefined.field3,
};

return myComplexObject;
}

Previously, all parameters were in "predefined", but now I need to fetch one(or more) from an external source and immediately return "myComplexObject" from the method without delay. How can I write the API call to avoid rewriting my code every time I need to add a new external call? Something like:

CallApi_1(paramForField3: string): Observable<int> {
return this.http.get(`${httpConfig.route}?$apply=filter${paramForField3}/groupby${httpConfig.groupingParam}`);
}

OR maybe

CallApi_1(paramForField3: string): Observable<int> {
return this.ExternalCallsService.GetParam3Information(paramForField3).subscribe(res => 
.GetParam3Information contains the same http call as above, but I need to do
something to return this result outside, I don't know what);
}

What I'm looking for is something like:

field3: isComplexCalculationsNecessary ? **await** this.CallApi(predefined.paramForField3) : predefined.field3,

Currently I am experimenting with 'rxjs' which offers interesting options for working with Observables, such as 'forkJoin', but I am not sure if I am on the right track. Maybe this kind of trick is not possible, or perhaps my understanding of Observables is incorrect and I should move complex logic to the back-end instead? Please advise.

It's important to emphasize once again that a simple ".subscribe" is not what I'm after because in all subscribe examples, values are not returned but assigned to global variables or directly to HTML elements, which is NOT what I require. I need to retrieve the value and continue working with it as soon as the external resource returns it.

Answer №1

If you want to see an example using rxjs/concat, check out this demo: https://example.com/rxjs-concat-demo

This code snippet demonstrates how you can execute functions in sequence, where each function returns an Observable:

let executionSequence = concat([
      this.first, 
      this.second, 
      this.afterSecond, 
      this.third]);

    executionSequence.subscribe(func => {
      func().subscribe(val => {
        this.results.push(val);
      })
    });

Answer №2

If you want to handle multiple HTTP calls in Angular, you have a few options. You can utilize operators such as zip or forkjoin (similar but not the same), or you can chain your HTTP calls together like this:

this.http.get1( url1, headers ).subscribe(
   data => {
      this.data1 = data;
      this.http.get2( url2, headers ).subscribe(
         data => {
            this.data2 = data;
         },
         error2{
            // deal with error2
         }
      )
   },
   error1 => {
      // handle error1
   }
)

While this approach may work fine, it's not the most elegant solution. I personally recall using the zip operator to solve a similar problem.

Edit : I found an example using the zip operator

     const  tpcomprob$ = this.data.getTPComprob( this.tpcomprobsId);
     const  comprobs$ = this.data.getComprobs(this.tpcomprobsId); 

     this.sbsComprobs = zip(tpcomprob$, comprobs$, (tpcomprob: any, comprobs: any) => ({tpcomprob, comprobs}))
                       .subscribe(pair => {
                          this.tpcomprob = pair.tpcomprob;
                          this.comprobs = pair.comprobs;

        },
        error => {this.httpError = error ;})
  });

Answer №3

Using forkJoin makes the process simple.

var _array = [];

_array.push(this.myService.method1());
_array.push(this.myService.method2());

forkJoin(_array).subscribe(resultList=>{
    //-- the results will be stored in an array
});

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

Are there any outcomes from using Angular in conjunction with httpService for POST and DELETE requests?

I've created an Angular service to handle all the HTTP requests necessary for my controllers to communicate with my API. export interface IDummyEntityApiService { getAllDummies() : ng.IPromise<Array<Entities.IDummy>>; } class DummyEn ...

Resolving Typescript jQuery AJAX Navigation Problem

Hello dear Earthlings, The code snippet below is currently implemented on my website brianjenkins94.me for handling basic navigation functionalities. After some recent changes, I encountered an issue with the #nav.on("click") event handler not working as ...

Issue encountered in Angular 2 rc.5 where the page fails to refresh after upgrading from rc.4

I recently updated my app from rc.4 to rc.5 and now I'm facing an unusual issue. Upon visiting localhost:8080, I am correctly redirected to localhost:8080/browse. However, when I refresh the page, I receive the error message: Cannot GET /browse. Pri ...

Guide on populating text boxes in a form automatically using ngFor?

As a beginner Angular developer, I am looking to automatically fill in text boxes in a form, specifically 10 text boxes (10 rows) using the ngFor directive. In my research on ngFor examples, I have noticed that most of them focus on populating a list base ...

Creating a file logging system with log4js to capture Console logs

Is there a way to automatically log all console logs, including failed expectations and exceptions, to a file without using try and catch in JavaScript? In Java's LOG4j, the rootlogger feature does this by default. Is there a similar functionality ava ...

Retrieving 'this' within the catch clause following the execution of a promise

When using the this keyword within a catch clause after initiating a promise, it displays "this" as undefined. Here is my scenario: I have a service with a Router object injected into its constructor. From a method in the service, an HTTP request is made t ...

The ng-template directive does not duplicate data, whereas HTML elements have the ability to showcase it

When trying to display JSON data using ng-template, I am facing issues as the data is not showing up. However, if I use HTML elements like div or span, it displays correctly. JSON format: const arr = [ { "date": 1, "color": "n ...

Storing and retrieving information in ag-grid using Angular

I have created two grids, Grid_A and Grid_B, both containing a column labeled "Activite". When the user edits cells in the "Activite" column in Grid_A, those same values are displayed in the corresponding column in Grid_B. This functionality is achieved th ...

Angular configuration for intercepting HTTP errors with RxJS Replay Subject

I am currently facing an issue where I am trying to retrieve the value of an error and show a customized error message using an HTML element. In order to manage the state of the error, I am utilizing a Replay Subject in my Interceptor. The interceptor is c ...

Unable to perform real-time transpilation of ES module, a loader plugin must be set up through the SystemJS.config configuration

I encountered an issue while trying to develop a plugable application. Everything was functioning correctly until I introduced "ngx-bootstrap" and "FullCalendarModule"/primeng in the plugin app. Importing any of these modules resulted in the following erro ...

Ionic 5 Virtual scroll leaves gaps where new items should be added

https://i.sstatic.net/y0lX7.png My goal is to display a list using ion-virtual-scroll, but I'm facing an issue where the new items are not showing up dynamically. Instead, they create blank spaces in the list. However, when I inspect the scroll, I ca ...

Uh oh! We encountered an error: Uncaught (in promise): Error: No routes found for the provided URL segment

There seems to be an issue with the router in my Angular application. I have successfully deployed it on an Apache server for production, and it is being served from the URL www.domain.com/clientng. Everything works fine, but I encounter an error in the br ...

Demystifying the Mechanics of RxJS Subscriptions during an HTTP Request

export class VendorHttpService { result = '0'; constructor(private http: HttpClient, private global: GlobalService) { } getProfileStatus(uid: String): string { this.http.get(this.global.getUrl()+"/vendor/profile-status/"+uid) ...

What are the best practices for testing a class function that executes a mongoose query?

Within my class, there are multiple class functions, with one specifically executing a mongoose query. The structure is similar to: export class ExampleService { constructor( @InjectModel(Example.name) private exampleModel: Model<Example>, ...

Defining assertions with specified type criteria

Looking to do something special in TypeScript with a class called Foo. I want to create a static array named bar using const assertion, where the values are restricted to the keys of Foo. This array will serve as the type for the function func while also a ...

Display a React element inside an array

There exists an array of items that each have a string defining them and an icon component: type Item = { Name: string; Icon: React.ElementType; }; export const ItemsList: Item[] = [ { Name: "Home", Icon: HomeIcon }, { Name: "Profil ...

Getting the value of an injected variable in a Vue.js computed method

I have utilized the provide/inject mechanism to pass data from a parent component to its grandchildren. However, in one of my components, I need to manipulate the data before rendering it in the template. My current setup looks like this: export default d ...

Ways to prevent encountering an npm error during the installation of a new package in an Angular application

For my Angular Application to update the date-time range picker, I needed to install an npm package. I opted to use ng2-daterangepicker, but encountered an error while trying to install its package. The error displayed is as follows : PS C:\Users&bso ...

Recursively transform JSON tree node elements into a single, cohesive JSON format

Seeking assistance with converting this JSON tree nodes into the final JSON structure by recursively joining the nodes. Any help would be greatly appreciated. I require a recursive function in JavaScript. Provided below is the sample input and the desired ...

Is it practical to utilize Angular and NestJS within a monorepository structure?

Is it advantageous to utilize Angular for the frontend and NestJS for the backend within a monorepo structure such as Nx or Lerna? What aspects of code could be effectively shared in this setup? One possibility is sharing Models, like a User-Class. Howeve ...