Kotai
Kotai

Reputation: 119

router.params.subscribe runs twice in succession

I am subscribing to my route params in angular but it keeps returning two values (the previous url and the present one), which messes up my code. I tried using the take operator to return only one instance of the params, but it returns the previous url instead.

Update: I edited the code to use the skip operator and the take operator and this time it does return the right params, but it still runs more than once which causes the array duplication and if I try to route to the same route again (which my situation requires), it doesn't get any params because I am skipping the first value

this.route.params.pipe(skip(1), take(1)).subscribe((params) => {
      console.log(params);
      if (params) {
        this.subscription = this.chatService.oneChannel(params['id']).subscribe((channel) => {
          this.channel = channel!;
          for (let i = 0; i < this.channel?.members!.length; i++) {
            this.chatService.getUserData(this.channel?.members![i]).pipe(take(1)).subscribe(result => {
              this.members.push(result!);
            })
          }
        })
      }
    })

Upvotes: 1

Views: 1242

Answers (1)

HassanMoin
HassanMoin

Reputation: 2184

I think you'll have to use a combination of switchMap and mergeMap/concatMap to achieve what you are trying to. Subscribe within a subscribe is not a good thing to do. Instead use the flattening operators that RxJS gives your nested subscriptions. There should only be a "single" subscription at the end of your observables' chain.

As a pseudocode, the above code should be similar to this

  this.activatedRoute.params
            .pipe(
                switchMap(params => {
                    return this.chatService.oneChannel(params['id']);
                })
            )
            .pipe(
                concatMap(channel => {
                    this.channel = channel!;
                    for (let i = 0; i < this.channel?.members!.length; i++) {
                        return this.chatService
                            .getUserData(this.channel?.members![i])
                            .pipe(take(1))
                            .subscribe(result => {
                                this.members.push(result!);
                            });
                    }
                })
            )
            .subscribe(response => {
                console.log(response);
            });

Upvotes: 2

Related Questions