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
}));
它提供了以下的輸出:
其中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));
}
這篇文章主要是由於我對這項技術缺乏瞭解,對此感到抱歉。但是,爲什麼我需要「扁平化」陣列?爲什麼要創建一個對象,因爲我們正在研究Obserbles,並且有兩個來源可以「合併」成一個對象(這只是一個意見)。我的理解是觀察者不可更新。 –
我已經用更詳細的解釋更新了我的答案。你應該嘗試看看egghead。io教程RxJS,他們真的很有幫助。 – AngularChef
謝謝你@AngularFrance。我需要自己進一步確定。 –