[英]Why first element of array is empty?
我有一個 function,它返回一個 Observable,一旦它觸發,我就會循環訂閱的數組
this.productService.getProductBySeo(proudctName).pipe(
catchError(e => of(null)),
this.unsubsribeOnDestroy
).subscribe(res => {
if (res) {
this.categoriesService.currentCategory.subscribe(menus => {
const activeElem = res;
const allItems = menus;
allItems.map(item => {
console.log(item)
console.log(item.id) // can see id of each elem
console.log(item.children) // first element of item.children is empty
....
更新 1
我已經按照評論中的建議更改為 switchMap,無論如何 arrays 是空的
this.productService.getProductBySeo(proudctName).pipe(
catchError(e => of(null)),
switchMap(res => {
this.categoriesService.currentCategory.subscribe(menus => {
if (menus) {
const activeElem = res;
const allItems = menus;
allItems.map(item => {
console.log(item)
// console.log(item.id) // can see id ,
console.log(item.children) // still empty :-(
item.children.map(item => {
// console.log(item);
return item
})
const fountObj = item.children.find(el => {
// console.log('element ', el)
return el === activeElem;
});
if (fountObj) {
this.totalStyle = item.seo_url; // to identify total style of the component
}
})
}
// console.log(menus)
})
return of(res)
}),
this.unsubsribeOnDestroy
).subscribe(res => {
if (res) {
this.product = res;
關於我希望看到的是當訂閱在this.categoriesService.currentCategory.subscribe
中觸發時,我想在控制台中看到item.children
。 正如我在記錄item.children
時只看到空數組,但是當我只控制台item
時,我可以看到item.children
在自己的數組中有 2 個項目
這不是一個很好的解決方案,但我懷疑它可能已通過其他地方的引用進行了更改。 嘗試深度克隆和循環。 IE
const allItems = JSON.parse(JSON.stringify(menus));
allItems.forEach(item => {
console.log(item)
console.log(item.children)
此外,在這種情況下,forEach 看起來比 map 好得多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.