0

I have a method in an angular component whose content is :

this.route.paramMap.pipe(
    switchMap((params: ParamMap) => {       
    let fooValue = params.get('selectedid');
    console.log("inside switch map with value as " + fooValue);
    return fooValue;
  })
)

This Observable is assigned to type Observable<string>. Now when I subscribe to above, and if selectedid = ABCD, then I get 4 invocations of the next() method one each for A, B, C, D. What is the reason for this?


This is happening only with switchMap and not with map operator.

When I use this.router.navigate(['/mypath', path.id]); and use a switchmap with it, it doesn't split the string. its happening with this.router.navigate(['/mypath1', { selectedid: obj.id, foo: "foo" }]); syntax

Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43
user2599052
  • 1,056
  • 3
  • 12
  • 27
  • 1
    It's happening because you use switchMap instead of map. switchMap is used when every event of the source observable must be "transformed" into events from another observable created from the original event. You don't want that here. You just want to transform a paramMap into a string. switchMap treats the string as an array of characters and emits one event per character. – JB Nizet Apr 06 '19 at 08:02
  • @JBNizet not sure abt the truth of above statement as when i use this.router.navigate(['/mypath', path.id]); and use a switchmap with it, it doesn't split the string. its happening with this.router.navigate(['/mypath1', { selectedid: obj.id, foo: "foo" }]); syntax – user2599052 Apr 06 '19 at 08:09
  • Well, in the first case, there is no string to split, since there is no selectedid parameter. See https://stackblitz.com/edit/angular-hdhyze (and open your browser console) – JB Nizet Apr 06 '19 at 08:16
  • @JBNizet the only difference I see between two forms is that in one case, observable is created out of string which is path.id and in other case, the observable is formed from object notation or object you might say. – user2599052 Apr 06 '19 at 08:56

1 Answers1

0

Try this

this.route.paramMap.subscribe(params => {
    this.id = params.get("selectedid")
    alert(this.id)
})
George C.
  • 6,574
  • 12
  • 55
  • 80
  • Whats the problem with the version I posted? – user2599052 Apr 06 '19 at 03:53
  • If the angular documentation was so clear, why would I post here? and your answer has clearly not answered my question. – user2599052 Apr 06 '19 at 09:06
  • I clearly asked in the first post. "what is the reason.". I am not interested in the solution. Don't worry much. I have seen lot of such arguments in SO and not so useful answers. – user2599052 Apr 06 '19 at 09:12