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。我需要自己进一步确定。 –