You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Angular中两个嵌套Observable合并为单个Observable?

问题描述

我想要把两个嵌套的Observable合并成一个。第一个Observable监听输入框的valueChanges事件,第二个Observable执行数据库查询操作。预期结果是得到一个能在Angular模板中配合async管道使用的Observable。

当前示例中,filteredUsers$变量的类型为Observable<Observable<MyUser[] | null>>,我需要将其转换为Observable<MyUser[] | null>类型。其中userControl是Angular的FormControl。

初始代码

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

编辑1

感谢@Jules的解答,问题已解决,修改后的代码如下:

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;
                    })
                );
        })
    );

内容的提问来源于stack exchange,提问作者user3241778

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 02:27:16