【问题标题】:How to avoid an infinite loop with Observables?如何避免 Observables 的无限循环?
【发布时间】:2017-02-09 16:53:14
【问题描述】:

我有以下代码:

ngOnInit(): void
    {  
    const source = this.categoryService.getCategories();
    console.log(source instanceof Observable);
    const example = source.map((categor) => categor.map((categories) => {
    const links = this.categoryService.countCategoryLinks(categories.id);
    const aff = example.merge(links).subscribe(linke => console.log(linke));
            return categories.id
        }));
    }

其中 getCategories() 返回一个 observable。

在这个 Observable 的每个项目上,我得到 categories.id 字段来运行另一个名为 countCategoryLinks(categories.id) 的方法,该方法也返回一个 Observable()。

我的问题是:我只有 3 个类别(ok),countCategoryLinks() 返回 3 个项目(ok),但上面的代码显示了 控制台中的无限循环。 出于测试目的“手动”启动的这两种方法都没有显示任何循环。

问题真的来自上面的代码。

有什么想法吗?

提前致谢和问候

【问题讨论】:

    标签: javascript angular typescript observable


    【解决方案1】:

    example.merge(links) map 回调创建的可观察对象,这将导致递归(即循环回自身)。这是使用适当缩进的好处,因为它更容易看到。

    ngOnInit(): void {  
        const source = this.categoryService.getCategories();
        console.log(source instanceof Observable);
        const example = source.map((categor) => categor.map((categories) => {
          const links = this.categoryService.countCategoryLinks(categories.id);
    
          // this line is the issue. You are using variable example which is being created by the callback this line of code is in
          const aff = example.merge(links).subscribe(linke => console.log(linke));
                  return categories.id
              }));
    }
    

    我在想,也许你的意思不是此时仍留在map 内?

    【讨论】:

    • 我正在尝试合并这两种方法的结果...这不是正确的方法吗?源包含 3 个项目。我从源中获取一个字段并启动另一种方法,获取一个可观察对象并将其合并到第一个...
    • @PhilippeCorrèges - 您可以在map 调用之外合并结果,或者合并在map 调用中生成的结果,但合并您当前所在函数的结果将导致一个无限循环(无限递归)。
    • 如果我在地图之外设置 const aff = example.merge(links).subscribe(linke => console.log(linke)); 就没有更多了链接 Observable() 的可见性。
    • @PhilippeCorrèges - 不清楚你在做什么以及为什么。你有example 一个可观察的类别。然后,您尝试将其与地图中每个类别的每个 links 可观察对象合并,您实际上在其中创建 example 可观察对象。好像逻辑不好……
    • @PhilippeCorrèges - 在您的代码中也不需要merge,因为source.map 的结果正在那个时间点实现。
    猜你喜欢
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    相关资源
    最近更新 更多