【问题标题】:How to properly inserting array to rxjs subject如何正确地将数组插入 rxjs 主题
【发布时间】: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 中使用异步管道展开,如下所示:&lt;ng-container *ngIf="geoLocation$ | async as geo"&gt;。这是唯一使用 observable 的地方,取消订阅应该对数组大小有任何影响。
  • 请检查 setLocations 调用了多少次..
  • @AndrewAllen 看到答案。 func 没有被多次调用,但是 observable 在 html 的 *ngFor 循环中被解包 arr.length num 次。谢谢!

标签: angular typescript rxjs


【解决方案1】:

好吧,我承认我是驴。在我的子组件中,我运行了一个 *ngFor 循环,而我打开 geolocations$ | async 的模板就在该循环内。 @Andrew Allen 建议查看主题的 next() 函数被调用了多少次,但是对于阅读此内容的任何人,请检查您的模板 observables 是否在 html 某处被多次解包。谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多