Kevin Malone
Kevin Malone

Reputation: 109

How can I extract the id from the url?

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

Upvotes: 1

Views: 2383

Answers (2)

LppEdd
LppEdd

Reputation: 21154

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'])
);

Upvotes: 2

Tony
Tony

Reputation: 20132

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']);
    )
}

Upvotes: 3

Related Questions