What is the best method for merging observable data in Angular?

My experience with RxJS and Async data is limited, and I have been struggling with nesting subscriptions when working with multiple data sources. I am curious about the correct approach to combine or utilize multiple data points, such as retrieving a user profile and their posts simultaneously. Below is my current implementation:

  constructor(private storage: AngularFireStorage, private db: AngularFirestore, private route: ActivatedRoute) {
    // Get profile
    this.route.paramMap.subscribe(params => {
      const profileName = params.get('id');
      const username = db.doc<any>('usernames/' + profileName).valueChanges();
      username.subscribe(val => {
        this.user = db.doc<User>('users/' + val.user).valueChanges();
        this.user.subscribe(val => {
          const userPosts = this.db.collection<Post>('posts', ref => ref.where('user', '==', val.uid)).snapshotChanges();
          this.posts = userPosts.pipe(map(actions => actions.map(a => {
            const data = a.payload.doc.data() as Post;
            const mediaUrl = this.storage.ref('post/m/' + data.mediaM).getDownloadURL();
            const userData: Observable<User> = db.doc<User>('users/' + data.user).valueChanges();

            return {mediaUrl, userData, ...data}
          })))
        });
      });
    });
  }

Answer №1

By using switchMap, you can seamlessly transfer the output from one observable to another without having to nest subscriptions.

this.route.paramMap.pipe(
  map(params => params.get('id')),
  switchMap(profileName => db.doc<any>('usernames/' + profileName).valueChanges()),
  switchMap(val => db.doc<User>('users/' + val.user).valueChanges()),
  switchMap(val => this.db.collection<Post>('posts', ref => ref.where('user', '==', val.uid)).snapshotChanges())
).subscribe(val => {});

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

Encountered an error while trying to install Npm, receiving a message stating "EINVAL: invalid argument

I have integrated the frontend-maven-plugin into my Java project to run my Angular App. The plugin configuration is as follows: <plugin> <groupId>com.github.eirslett</groupId> <artifactId>frontend-mav ...

Error: Uncaught TypeError - The function boss.SetBelongToClan is not defined

Currently, I am faced with an issue while working on a typescript and sequelize project within an express application. The problem arises when trying to create a type-safe interface for utilizing the associate function. Within my Instance interface, there ...

Deducing data types from arrays containing both narrow and wide elements

const ElemText = { value: string }; const ElemData = { value: string, numId: number }; function combineElements( elementsText: Array<ElemText>, elementsData: Array<ElemData> ) { const combinedElements = [...elementsText, ...elementsData ...

Utilizing Typescript Decorators to dynamically assign instance fields within a class for internal use

I am interested in delving into Typescript Decorators to enhance my coding skills. My primary objective is to emulate the functionality of @Slf4J from Project Lombok in Java using Typescript. The concept involves annotating/decorating a class with somethin ...

Exploring the (*ngFor) Directive to Iterate Through an [object Object]

Attempting to iterate through the array using *ngFor as shown below. let geographicalArea = [{ "_id": "5e77f43e48348935b4571fa7", "name": "Latin America", "employee": { "_id": "5e77c50c4476e734d8b30dc6", "name": "Thomas", ...

Leveraging local libraries with Angular

After setting up two local libraries: ng new my-library --create-application=false ng generate library core ng generate library shared The shared library utilizes the core library as shown below: import { CoreModule } from 'core'; @NgModule({ ...

Ways to insert script tag in a React/JSX document?

private get mouseGestureSettingView() { const {selectedMenu} = this.state; return ( selectedMenu == 2 ? <script src="../../assets/js/extensions/mouse-gesture/options.js"></script> <div className={styles.settingForm}& ...

Encountered an error while attempting to load resource: server reported a 500 status code. React application successfully hosted on Vercel

Hey there, I'm encountering an error on the deployed version of my Max app. The app is hosted on Vercel, and whenever I try to log in, I get this server error message: "Server error There is a problem with the server configuration. Check the server lo ...

Utilize the useState() hook to add an object and display its data in a React Native

Here is a function I am working with: const [dataLoc, setDataLoc] = useState({date: "No data received yet from sensor", coords: {}}); This is where I set the location: Geolocation.getCurrentPosition( location => { const date = d ...

Steps for transferring data between two components

I'm looking for a way to transfer an object's id from one component to another. <ng-container matColumnDef="actions"> <mat-header-cell *matHeaderCellDef></mat-header-cell> <mat-cell *matCellDef="let user"> ...

Trouble with importing React JSX from a separate file when working with Typescript

This problem bears some resemblance to How to import React JSX correctly from a separate file in Typescript 1.6. Everything seems to be working smoothly when all the code is contained within a single file. However, as soon as I move the component to anoth ...

No solution was found for implementing Airbnb TypeScript in React.js (Next.js) using ESLint

screenshot I encountered an issue where I couldn't locate the Airbnb typescript option in React JS (Next JS) within ESLint. Prior to this, I had installed Storybook and mistakenly clicked "yes" when prompted to migrate ESLint to Storybook. ...

What is the best way to include a PHP mail file in an Angular project?

I have recently developed a single-page application using Angular that features a contact form. To handle the functionality of this contact form, I opted to use the PHP mail function. The PHP file responsible for handling the form submissions is located wi ...

Troubleshooting: Vue 3 Vite encountering 404 error when attempting to load fonts from assets using Font Loading API

Attempting to dynamically load fonts from the assets directory within Vue 3 (Typescript) using Vite has led to a 404 error occurring. https://i.sstatic.net/H3Ho7.png const fonts = import.meta.glob('@/assets/fonts/*.otf') console.log(fonts) asy ...

activate the change detection for a specific subcomponent

Let's say I am conducting a test on MyComponent, which has a template that includes SubComponent The structure of MyComponent is as follows @Component({ selector: 'my-component', template: ` <sub-component [input]="property"> ...

Utilizing Lazy Loading Modules within an Angular 2 (v5) App

I'm struggling to implement lazy loading in my Angular 2 (version 5.1.3) project. While following Todd Motto's guide on Lazy Loading Code Splitting, I am hitting a roadblock in getting it to function correctly. My app consists of multiple modul ...

When using Angular 8 with RxJs, triggering API calls on click events will automatically detach if the API server is offline

I have an Angular 8 application with a form containing a save button that triggers a call to a Spring Boot microservice using RxJs. I decided to test what would happen if the Rest API server were down. When the Rest API is running, clicking the button wor ...

Locking state object and properties as read-only in ReactJS/Typescript

I have an object from a third-party class and I want to ensure that its properties are read-only. This means that I do not want to be able to change the state with this.state.object.props = "xx"; The structure of the object is as follows: class ThirdPart ...

Angular 2 encountering CORS issues on Chrome

When I attempt to access a SOAP webservice deployed on WebLogic and developed in Java using JAX-WS, I encounter an issue where IE11 successfully retrieves the response while Chrome returns the following error: Response to preflight request doesn't pa ...

Nesting two ngFor loops in Angular using the async pipe leads to consistent reloading of data

In my Angular application, I am trying to retrieve a list of parent elements and then for each parent, fetch its corresponding children (1 parent to n children). Parent Child1 Child2 Parent Child1 Parent3 Child1 Child2 Child3 Initially, I succes ...