2017-02-14 117 views
0

我有這樣一段代碼:如何「同步」Observable?

ngOnInit(): void 

     { 
this.categories = this.categoryService.getCategories(); 

      var example = this.categories.flatMap((categor) => categor.map((categories) => { 

      var links = this.categoryService.countCategoryLinks(categories.id) 
         .subscribe(valeur => console.log(valeur)); 
       return categories.id 
      })); 
    } 

結果是兩個觀測。 一個包含在一個類別列表中。 第二個是特定categories.id的項目數量。

我的問題是如下:

我怎麼能得到所有這些信息在特定的數據結構構成的? 我想將類別和每個類別的項目數量存儲在相同的數據結構中,以便能夠在我的TS組件中顯示它們。

我一步一步走到試圖解決我的問題,我去有下面的代碼,這幾乎是該解決方案:

this.categories = this.categoryService.getCategories(); 
     var example = this.categories.mergeMap((categor) => categor.map((myCateg) => 
      { 
      this.categoryService.countCategoryLinks(myCateg.id) 
       .map(numlinks => Object.assign(myCateg,{numLinks: numlinks})) 
        .subscribe(valeur => console.log(valeur)); 
      return myCateg.id 
     })); 

它提供了以下的輸出:

enter image description here

其中numLinks仍然是一個對象...(包含我的計數值)任何想法如何將其轉換爲json屬性,如categoryName或id?

在此先感謝和問候,

這裏是解決的問題:

ngOnInit(): void 
{ 
    this.categories = this.categoryService.getCategories(); 
    const example = this.categories 
     .mergeMap((categor) => categor 
      .map((myCateg) => { 
     this.categoryService.countCategoryLinks(myCateg.id) 
      .map(numlinks => { 
       myCateg.numlinks = numlinks.count; 
       return myCateg; 
      }) 
       //Object.assign(myCateg,{numLinks: numlinks})) 
      .subscribe(value => console.log(value)); 
     return myCateg 
    })); 

      example.subscribe(val => console.log("value2: "+val)); 

} 

回答

1

再次,解決方案來自mergeMap()操作。 :-)

this.categoryService.getCategories() 
    .mergeMap(val => val) // "Flatten" the categories array 
    .mergeMap(category => 
    this.categoryService.countCategoryLinks(category.id) 
     // Write the number of links on the `category` object 
     .map(numLinks => Object.assign(category, {numLinks: numLinks})) 
) 
    .toArray() 
    .subscribe(allCategoriesWithNumLinks => console.log(allCategoriesWithNumLinks)); 

我不打算進入細節(第mergeMap扁平化陣列,Object.assign(),產生最終的對象),因爲它看起來像我們涵蓋了所有在以前的線程,我們有,但如果有任何不清楚的地方,請隨時提問。

菲利普的問題:

  • 爲什麼拼合類數組?我假設getCategories()發出一個包含所有類別的單數組。既然你想爲每個類別運行一個HTTP請求,那麼讓每個類別都有一個獨立的可觀察對象會更方便。這就是第一個mergeMap()所做的:它將Observable<Category[]>轉換爲Observable<Category>
  • 爲什麼要創建一個對象?你說過你想把所有的東西都存儲在同一個數據結構中。這就是Object.assign所做的:它爲category對象本身寫入每個類別的鏈接數量。這樣,你最終得到一個包含來自兩個觀測值(類別+ numLinks)的信息的對象。
+0

這篇文章主要是由於我對這項技術缺乏瞭解,對此感到抱歉。但是,爲什麼我需要「扁平化」陣列?爲什麼要創建一個對象,因爲我們正在研究Obserbles,並且有兩個來源可以「合併」成一個對象(這只是一個意見)。我的理解是觀察者不可更新。 –

+0

我已經用更詳細的解釋更新了我的答案。你應該嘗試看看egghead。io教程RxJS,他們真的很有幫助。 – AngularChef

+0

謝謝你@AngularFrance。我需要自己進一步確定。 –