如何从网址中提取ID?

时间:2019-08-22 07:55:24

标签: javascript angular typescript ecmascript-6 single-page-application

网址看起来像这样:

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

我正在尝试提取ID部分(RECd4teOsdsro9YRcOMX)

我尝试了以下操作:

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
}

如何从网址中提取ID并将其保存到变量chatRoomUid中?

路线:

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

编辑:添加了路线

2 个答案:

答案 0 :(得分:2)

您可以像这样定义您的路线

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

然后在您的组件中简单地

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

constructor(private route:ActivatedRoute){}

ngOnInit(){
    this.route.params.subscribe( params =>
        console.log(params['chatRoomUid']);
    )
}

答案 1 :(得分:2)

您正在console.log处于不同的环境中。
请记住,Observable是异步的,因此您必须在console.log内移动switchMap

不过,只需生成一个新的Observable

chatRoomUid$: Observable<string>;

...

this.chatRoomUid$ = this.route.params.pipe(
  map(params => params['roomUid'])
);