1

The url looks like this:

http://localhost:4200/room/RECd4teOsdsro9YRcOMX/chat

I'm trying to extract the id part (RECd4teOsdsro9YRcOMX)

I tried the following:

chatRoomUid: string;

constructor(
  private route: ActivatedRoute
) {}

ngOnInit() {
  this.chatRoom$ = this.route.parent.parent.params.pipe(
      tap(params => this.chatRoomUid = params.chatRoomUid),
      switchMap(params => {
        if (!params.chatRoomUid) return of(null);
        this.chatRoomUid = params.chatRoomUid;
      })
    );

    console.log(this.chatRoomUid); // returns undefined
}

How can I extract the id from the url and save it to my variable chatRoomUid?

Route:

{ path: 'room/:roomUid', loadChildren: () => import('@chatapp/pages/room/room.module').then(m => m.RoomModule) },

Edit: Added the routes

Tony Ngo
  • 19,166
  • 4
  • 38
  • 60
Kevin Malone
  • 99
  • 1
  • 11
  • How does your route look like? It should look something like this: `{path: 'room/:chatRoomUid/chat', component: ChatComponent}` see https://angular.io/guide/router#configuration – Stefan Falk Aug 22 '19 at 08:01
  • Please add the routes in your question. – nash11 Aug 22 '19 at 08:01
  • Possible duplicate of [How to get param from url in angular 4?](https://stackoverflow.com/questions/45997369/how-to-get-param-from-url-in-angular-4) – jitender Aug 22 '19 at 08:07
  • duplicate of https://stackoverflow.com/questions/45997369/how-to-get-param-from-url-in-angular-4/47382088 – jitender Aug 22 '19 at 08:07

2 Answers2

2

You can define your route like this

{path: 'room/:chatRoomUid/chat', component: ChatComponent}

Then in your component simply

import {ActivatedRoute} from '@angular/router';

constructor(private route:ActivatedRoute){}

ngOnInit(){
    this.route.params.subscribe( params =>
        console.log(params['chatRoomUid']);
    )
}
Tony Ngo
  • 19,166
  • 4
  • 38
  • 60
2

You're console.loging in a different context.
Remember Observables are asynchronous, thus you'd have to move console.log inside switchMap.

However, just produce a new Observable

chatRoomUid$: Observable<string>;

...

this.chatRoomUid$ = this.route.params.pipe(
  map(params => params['roomUid'])
);
LppEdd
  • 20,274
  • 11
  • 84
  • 139