2017-02-09 13 views
0

Iは、次のコードを有する:Observablesで無限ループを回避する方法は?

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()観察を返しを。この観測の各項目に

は、私が countCategoryLinksと呼ばれる別の方法を実行するためにcategories.idフィールドを取得する(categories.id)も観察可能返し()。

私は3つのカテゴリ(ok)、countCategoryLinks()は3つのアイテム(ok)を返しますが、上のコードはコンソールの無限ループを示しています。 どちらの方法もテスト目的で "手動で"開始してもループを表示しません。

問題は実際に上記のコードから来ています。

事前に感謝し、よろしく

答えて

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の内側にあることを意味しなかった考えていますか?

+0

私は両方のメソッドの結果をマージしようとしています...これは正しい方法ではありませんか?ソースには3つの項目があります。ソースからフィールドを取得し、他のメソッドを開始し、観測可能にして最初にマージします。 –

+0

@PhilippeCorrèges - 結果を 'map'呼び出しの外にマージするか、生成された結果を'あなたが現在いる関数の結果をマージすると、無限ループ(無限再帰)につながります。 – Igor

+0

** const aff = example.merge(links).subscribe(linke => console.log(linke)); **マップの外に、Observable()リンクの可視性はありません。 –

関連する問題