繁体   English   中英

Angular 订阅链可观察

[英]Angular subscribe to chain observable

我有一个服务,用于链接一组 http 请求并返回产品列表。 这是我到目前为止:

listForDisplay(categoryId: string): Observable<any[]> {
    if (!categoryId) return of([]);
    return this.listFields(categoryId);
}

private listFields(categoryId: string): Observable<any[]> {
    return this.fieldService.list(categoryId, true).pipe(
        flatMap((fields: Field[]) => {
            if (!fields) return of([]);
            return this.listProducts(categoryId, fields);
        }),
    );
}

private listProducts(categoryId: string, fields: Field[]): Observable<any[]> {
    return this.productService.listSpecificationProducts(categoryId).pipe(
        flatMap((products: any[]) => {
            if (!products) return of([]);
            return this.mapVisibleFields(fields, products);
        }),
    );
}

private mapVisibleFields(fields: Field[], products: any[]): any[] {
    console.log(products);
    return this.productModelService.mapProductsWithSpecificationFields(fields, products);
}

在我的控制器中,我称之为:

private getCategory() {
    this.selectorSubscription = this.selectorService.category.subscribe(categoryId => {
        this.products = [];
        this.specificationService.listForDisplay(categoryId).subscribe((products: any[]) => {
            console.log(products);
            this.products = products;
        });
    });
}

问题是第一部分中的console.log返回一个数组。 控制器中的console.log只返回一个项目....

像这样:

在此处输入图片说明

我显然做错了什么。 任何人都可以帮忙吗?

根据 rxjs 文档,flatMap

将每个源值投影到一个 Observable 中,该 Observable 合并在输出 Observable 中。

这就是为什么您的订阅被多次调用,每个值一次一个。 你确定你需要 flatMap 吗? 从您尝试做的事情看来, map会更合适。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM