【发布时间】:2019-10-23 17:07:47
【问题描述】:
当我将数组插入 rxjs 主题时,我得到了 3 次相同的数组。
父组件:
const geoExistsArr: { lat: number, lng: number }[] = [];
for (let i = 0; i < x.length; i++) {
for (let j = 0; j < requiredKeys.length; j++) {
// Some logic
}
if (has(x[i].data, 'lat') && has(x[i].data, 'lng')) {
// Pushing to array
const { lat, lng } = x[i].data;
geoExistsArr.push({ lat, lng })
}
}
console.log(geoExistsArr)
// Adding the array to subj.
this.locationSrv.setLocations(geoExistsArr)
服务:
setLocations(loc: ILocation) {
this.geoArray = [...this.geoArray, loc]
this.geoSubj$.next(this.geoArray)
}
子组件(显示来自主题的值):
this.geoLocation$ = this.locationSrv.geoCoordinates$.pipe(
switchMap((geo, idx) => {
console.log(geo, idx) // <- problem here. this guy prints 3 times.
geo.forEach(g => {
console.log(g)
requests.push(this.locationSrv.getAddressByLatLng$(g))
});
return concat(...requests).pipe(
toArray()
)
}),
应该发生什么: 我将单个数组存储到主题。
我已经对这个错误视而不见,所以任何帮助将不胜感激!
【问题讨论】:
-
我猜 geoLocation$ 是订阅。您需要在 ngOnDestroy() 方法中取消订阅。每当组件加载时,它都会启动订阅并一直保持到您取消订阅为止。在您的情况下,多个订阅可能已经开始。这就是为什么你会重复价值观。只需在 ngOnDestroy 上结束订阅 :)
-
你在哪里订阅 this.geoLocation$ ?
-
@HVSharma & @Fateme Fazli:它在子 html 中使用异步管道展开,如下所示:
<ng-container *ngIf="geoLocation$ | async as geo">。这是唯一使用 observable 的地方,取消订阅应该对数组大小有任何影响。 -
请检查 setLocations 调用了多少次..
-
@AndrewAllen 看到答案。 func 没有被多次调用,但是 observable 在 html 的 *ngFor 循环中被解包 arr.length num 次。谢谢!
标签: angular typescript rxjs