网址看起来像这样:

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
}


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

路线:

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


编辑:添加了路线

最佳答案

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

但是,只需生成一个新的Observable

chatRoomUid$: Observable<string>;

...

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

09-07 13:04