Combine two observables that are nested inside each other into a single observable

Combining two nested observables into one is my goal. The first observable listens for valueChanges on an input, while the second queries the database. I expect to have a single observable that I can utilize with an async pipe in my Angular template.

In the example provided, the filteredUsers$ variable is currently of type

Observable<Observable<MyUser[] | null>>
, but my aim is to simplify it to just
Observable<MyUser[] | null>
.

The userControl represents an Angular FormControl.

this.filteredUsers$ = this.userControll.valueChanges.pipe(debounceTime(300)).pipe(
        switchMap((newSearch) => {
            if (newSearch === null) {
                return of(null);
            }
            return this.userSearchGql
                .fetch({
                    where: {
                        OR: [
                            { firstname: { contains: newSearch } },
                            { secondname: { contains: newSearch } },
                            { email: { contains: newSearch } }
                        ]
                    }
                })
                .pipe(
                    map((res) => {
                        return res.data.users;
                    })
                );
        })
    );

Edit 1

I believe the issue has been resolved with the assistance of @Jules' response

Answer №1

If you want to switch observable, consider using the SwitchMap operator.

this.filteredUsers$ = this.userControll.valueChanges.pipe(debounceTime(300)).pipe(
        map((newSearch) => {
            if (newSearch) {
                return switchMap((newSearch) => this.userSearchGql
                    .fetch({
                        where: {
                            OR: [
                                { firstname: { contains: newSearch } },
                                { secondname: { contains: newSearch } },
                                { email: { contains: newSearch } }
                            ]
                        }
                    }))
            }
            return null;
        }),
        map((res) => {
           return res ? res.data.users : null;
        })
    );

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 icon for the ng-bootstrap datepicker calendar is not showing up

I recently implemented a date picker using angular-cli and ng-bootstrap. The datepicker is working perfectly after installing it from npm and adding it to the main module. However, I am facing an issue with the icon not displaying properly. Check out the ...

The inference of optional generic types is not occurring

I need help addressing a type error in my TypeScript wrapper for handling NextJS API requests. Specifically, I am facing an issue when trying to pass a single type for one of the generic types in the function. To illustrate this error, I have created a si ...

What could be causing the RxJS Observable to malfunction within a Vue.js app container?

Can anyone explain why the RxJS Observable in the "whatever" div is functioning properly, while the one in the app div for Vue.js is not working? (I am aware of modules that can bridge the gap between Vue.js and RxJS on NPM, but I am curious about why the ...

Troubleshooting the carouselExampleIndicators issue in Angular 4

I successfully implemented a carousel on my webpage using the code below: <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicat ...

Using Angular, you can incorporate a link declared in the controller directly into your template

Hey there everyone, hope you're having a good morning. As mentioned in the title I am looking to define a link as a string and then use it in the template. Below is the code snippet I have written for it .ts array=["<a href=\"https://exam ...

Is it feasible to have two interfaces in Typescript that reference each other?

I am facing an issue with two interfaces, UserProfile and Interest. Here is the code for both interfaces: export default interface UserProfile { userProfileId: string, rep: number, pfpUrl: string, bio: string, experience: "beginner" | " ...

Updating data in parent state with angular 2 ui-router

I am working on a project that utilizes Angular 2 and UI-ROUTER (not NgRoute). The project includes: a parent state 'parent', which controls the view of Header and Control as depicted in the image below, two child states 'childA ...

How can I eliminate the immediate forward slash (/) following a hash (#) in an Angular application

After configuring my angular 8 app routing with {useHash:true}, I encountered an issue. Whenever I open a URL in the browser, such as https://localhost:4200/#/todo https://localhost:4200/#/todo/12 I do not want that additional "/" immediately after "#". ...

Issue: Expressjs is throwing a TypeError due to an attempt to read the 'id' property of undefined

I am currently working on a registration function in expressjs, but I keep encountering the following error message: TypeError: Cannot read properties of undefined (reading 'id') This is my user model: Users.ts interface UserAttributes { id: ...

The module 'csstype' is nowhere to be found, according to error code TS2307

I've encountered an issue with Visual Studio 2017 not compiling my code. Recently, I integrated Typescript, React, and Webpack into our solution, and everything seemed to be working fine. However, upon attempting to build our MVC application, it star ...

Unable to locate the module 'next' or its associated type declarations

Encountering the error message Cannot find module '' or its corresponding type declarations. when trying to import modules in a Next.js project. This issue occurs with every single import. View Preview Yarn version: 3.1.0-rc.2 Next version: 1 ...

What is the best method for generating a GUID in Angular 2?

I'm currently working on an application where I require generating a unique GUID to use as cookies. Does anyone have insight on how to create a GUID in Angular 2 with Typescript? Alternatively, is there any Angular 2 dependency or library that can ass ...

The combination of React, Typescript, and MaterialUI Paper results in a stunning design with a sleek and

Whenever I include <Paper elevation={0} /> within my react component, I encounter the following issue: Cannot read properties of undefined (reading 'background') TypeError: Cannot read properties of undefined (reading 'background&apos ...

Is Angular CLI essential for building Angular applications?

Recently started working on a new project that uses Angular and I noticed in the package.json file these dependencies are listed: "@angular/common": "~8.0.0", "@angular/compiler": "~8.0.0", "@angular/core": "~8.0.0", "@angular/forms": "^8.0.3", "@angular/ ...

Retrieve a multitude of nested Records within the returnType that correlate with the number of arguments provided to the function

My goal is to dynamically define a deeply nested ReturnType for a function based on the number of arguments passed in the "rest" parameter. For example, if we have: getFormattedDates( dates: Date[], ...rest: string[] // ['AAA', 'BBB&apos ...

Navigating through different components in Angular2 is made simple with the

Struggling to create a single-page app and facing issues with routing. Despite following several tutorials, I find them quickly becoming outdated due to Angular2 still being in beta. Whenever any reference to router directives, configurations, or provider ...

Eliminate any repeated elements in the array by utilizing TypeScript

Hey, I'm trying to figure out how to remove duplicate entries from an array where the UserId values are the same, and keep only one of each unique entry. Can anyone help me with this? For example: a=[ {userId:1,name:''}, {userId:2,name:&apo ...

Angular and TypeScript make a powerful combination when working with the mat-table component

I'm currently working with Angular's mat-table component. One challenge I'm facing is setting a caption for the table. <table mat-table [dataSource]="dataSource" class="mat-elevation-z8" id=tbl_suchergebnis> <caption> ...

Utilizing Angular 2+: How to Retrieve Query Parameters in a Route Transition, Not the Currently Active Route

Issue: I am facing a challenge in accessing query parameters that a route guard is checking, rather than the query parameters of the current URL snapshot. The ActivatedRoute only displays the current route status, not the route in transit. For example, wh ...

Having trouble integrating SVG icons into my Angular project

I'm encountering an issue with adding icons that I've designed in Figma to my web application. Some of the icons are displaying correctly while others are not. Here is the code snippet I am using to add the icons: .dx-icon-info { mask-image: ...