What is the best way to link together a varying amount of observables?

Being new to Angular and Observables, I am looking for a way to efficiently chain the call of a service multiple times. Is there a straightforward method using Observables that can achieve this in a more generic manner than traditional methods? (similar to this example).

this.myService.getNodeById(res.parent_id).subscribe(res => {
  this.myService.getNodeById(res.parent_id).subscribe(res => {
     this.myService.getNodeById(res.parent_id).subscribe(res => {
        // logic here as long as res.parents_id is present
     });
  });
});
  • angular: 12.0.5
  • typescript: 4.2.3
  • rxjs: 6.6.0

Answer №1

To create a recursive method for retrieving nodes by their IDs, consider implementing the following code snippet:

fetchNodeByID(id) {
  return this.customService
    .getNodeById(id)
    .pipe(switchMap((result) => (result.parent_id ? this.fetchNodeByID(result.parent_id) : of(result))));
}

Answer №2

If you want to create a unique Rx.js operator, consider implementing one that integrates the necessary API calls within switchMap.

type GetNodeFunction<TNode = any, TResponse = any> = (
  response: TNode
) => Observable<TResponse>;

// Define custom getNode operator
function fetchNode<TNode>(getNodeFunction: GetNodeFunction) {
  return (observable: Observable<TNode>) =>
    observable.pipe(switchMap((response) => getNodeFunction(response)));
}

this.myService.getNodeById(response.parent_id).pipe(
  fetchNode((response) => this.myService.getNodeById(response.parent_id)),
  fetchNode((response) => this.myService.getNodeById(response.parent_id))
);

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

Errors occur when attempting to parse Uint8Array in Typescript

I received the following object as a response from calling the AWS Lambda client in NodeJS. { '$metadata': { httpStatusCode: 200, requestId: '1245', extendedRequestId: undefined, cfId: undefined, attempts: 1, tot ...

Can TypeScript and JavaScript be integrated into a single React application?

I recently developed an app using JS react, and now I have a TSX file that I want to incorporate into my project. How should I proceed? Can I import the TSX file and interact with it within a JSX file, or do I need to convert my entire app to TSX for eve ...

Loading an Angular 2 application or component through an HTTP request can be done by following

Is there a way to dynamically load an Angular2 application or component from a remote server using HTTP? For example: Template: <app-local></app-local> <app-http></app-http> Sample code for AppComponent of app-local: [...] load ...

Experiencing a type error within Redux in a React Native project utilizing TypeScript

I am currently working on implementing a feature to store the boolean value of whether a phone number is verified or not. Within my login component: await dispatch(setOTPVerified(data.is_phone_verified)); Action.tsx: export const OTP_VERIFIED = 'OTP ...

An iron-dropdown made of polymer featuring a trigger button made of paper-icon-button

I am facing an issue on my Angular site where I have integrated Polymer. I am trying to add a notifications section to the header, but I am struggling to make the button functional. How can I bind the click event of the button to trigger the dropdown? Thi ...

...additional properties in React function components using TypeScript

Here is a snippet of code that I am working with: <InputComponent id="email" name={formik.values.email} type="text" formik={formik} className="signInInput" disabled/> However, there seems to be an issue with the disable ...

Transforming the setting into redux using setTimeout

I am currently working with the following context: interface AlertContextProps { show: (message: string, duration: number) => void; } export const AlertContext = createContext<AlertContextProps>({ show: (message: string, duration: number) =&g ...

What is the reason for the manual update of a view when copying an object's attributes into another object, as opposed to using Object.assign()?

In my application, I have a parent component called 'EmployeeComponent' that is responsible for displaying a list of employees. Additionally, there is a child component named 'EmployeeDetailComponent' which displays the details of the s ...

What separates the act of declaring a generic function from explicitly declaring a type for that very same generic function?

Here are two instances demonstrating the use of a generic function: function myGenericFunction<TFunc extends Function>(target:TFunc): string { return target.toString(); } Based on this response, this represents a declaration for a generic funct ...

Capture stunning photos with Ionic Capacitor CameraPreview, where the camera is always front and center. Say goodbye to any

I'm currently working on developing a customized camera feature for a tablet application. One of the challenges I'm facing is getting buttons to float over the camera preview. Despite setting the isBack attribute to true, the camera preview remai ...

The module 'AppModule' is throwing an error with the declaration of 'CacheService'. Make sure to include a @Pipe, @Directive, or @Component annotation to resolve the issue

I'm currently implementing client-side caching in my project by following the code examples from this blog post. After adding the cache.service.ts and http-client.service.ts code, I integrated them into a component that triggers the code. However, I ...

Encountered an eas error during Android build process

When I try to execute the command "eas build --platform android" I encounter the following error message: "✖ Build failed ...

Tips for utilizing parameters within SQL Server

Hello everyone! I am new to SQL Server in Azure functions using Typescript. I am currently facing an issue while trying to update a row in the database using declared variables, particularly with VARCHAR types. Strangely, it works fine in the database tool ...

Creating a multi-level signup page in Angular 4 using Bootstrap

Currently, I am working with angular 4 and bootstrap 4 to create a multi-level sign-up page. One of the challenges I am encountering is how to properly include a JavaScript file into my angular project. import '../../../assets/js/js/multiform.js&apo ...

Using the Vue.js Compositions API to handle multiple API requests with a promise when the component is mounted

I have a task that requires me to make requests to 4 different places in the onmounted function using the composition api. I want to send these requests simultaneously with promises for better performance. Can anyone guide me on how to achieve this effic ...

A solution for resolving the RuntimeException in genuitec's TypeScript Editor for Eclipse Oxygen

After setting up a fresh Eclipse Oxygen and installing the Angular IDE from Genuitec, I encountered an issue on the second day when I opened a project and accessed a *.ts File. The error message displayed was: java.lang.RuntimeException: java.lang.Illegal ...

How can I prevent all permission requests in Electron Security?

I'm currently in the process of enhancing the security of my Angular/Electron application. For this purpose, I decided to utilize electrongravity which has proven to be effective in identifying misconfigurations and prompting me to establish a permis ...

What is the process for updating the internal TypeScript version in VS Code?

When using VS Code, I noticed it comes with its own TypeScript version: Is there a way to update this? The current version is 4.9.3. https://i.sstatic.net/vEx85.png ...

Use `$$state: {…}` within the request rather than the data

When attempting to send a request with data, I am only getting "f {$$state: {…}}" in the console. $scope.createTask = function () { var req = $http.post('api/insert', { title: $scope.newTitle, description: ...

What is the best way to create a jumping animation for an object in Cannon.js and Three.js?

During my quest for a solution, I came across a common practice where users used cannonBody.velocity.y = JUMP_VELOCITY to make an object jump. However, in my scenario, this method only worked while the object was already in motion and not when it was stat ...