我想创建一个动态菜单栏,方法是从两个集合(supcat和cat)中获取数据,然后将两者组合以创建一个新数组,我将在页面加载菜单时访问该数组,但push()无法正常工作。
ngOnInit() {
this.cattest();}
cattest(){
var x;
this.supcatobj.fetchsupcat().subscribe(
(res)=>
{
if(res.length!=0)
{this.supcat=res;
for(let x=0;x<this.supcat.length; x++)
{
this.catobj.fetchallcat(this.supcat[x]["_id"]).subscribe(
(resp)=>
{
this.allcat=resp;
for(let y=0;y<this.allcat.length;y++)
{
}
this.testarr[x].push(this.supcat[x]["supcatname"],this.allcat);
}
);
}
}
}
);}
答案 0 :(得分:0)
我将尝试为两个不同的集合编写单独的可观察对象,而不是嵌套subscribe()调用,然后使用combinateLatest()运算符将它们组合到所需的数组中。很难确切地看到您正在做什么,但是从概念上讲,它会是这样的:
const supcat$ = this.supcatobj.fetchsupcat().pipe(filter(cat => cat.length > 0));
const allCat$ = this.catobj.fetchallcat();
const combinedCats$ = combineLatest(supcat$, allCat$);
const res$ = combinedCats$.pipe(map(res => {
// do operation that involves both data sets
});
请记住map()将返回一个新数组。这样,您只需要预订一个变量,并且如果将其放在类级别,则可以在模板中使用异步管道(|),这样它将自动退订。