如何从路由参数获取id并传入服务

时间:2017-10-18 13:20:34

标签: angular

用户点击一个按钮,该按钮应将其带到个人资料/:ID页面。在配置文件组件中,我尝试获取id route params并将其传递给我的用户服务,以返回用户对象以在html中打印。但是,这不起作用。

main.component.html

  <button mat-icon-button color="accent" matTooltip="Account" [matTooltipPosition]="toolTipPosition" [routerLink]="['profile', user?._id]">
                <mat-icon>account_box</mat-icon>
          </button>

主routing.module.ts

  {
    path: 'profile',
    loadChildren: '../profile/profile.module#ProfileModule',
  },

profile.component.ts

constructor(private authService: AuthService,
    private route: ActivatedRoute,
    private router: Router,
    private userService: UserService) { }

ngOnInit() {
    this.user = this.route.paramMap.switchMap((params: ParamMap) => {
        let user_id = params.get('id');

        return this.userService.get(user_id);
    });
}

profile.component.html

{{ user?._id}}

轮廓routing.module.ts

  {
        path: '',
        component: ProfileComponent,
        children: [
            {
                path: ':id',
                component: HomeComponent,
                children:
                [
                    { path: 'home', component: HomeComponent },
                    { path: 'moments', component: MomentsComponent },
                ]
            },

        ]
    },

2 个答案:

答案 0 :(得分:1)

您需要订阅paramMap可观察序列。默认情况下,Observable是冷的,因此在您订阅它们之前它们不会运行。

ngOnInit() {
    this.route.paramMap.switchMap((params: ParamMap) => {
        let user_id = params.get('id');

        return this.userService.get(user_id);
    })
    .subscribe(res => this.user = res); // assuming user is being returned from this.userService.get()
}

此外,您不需要this.user = this.route.paramMap...,this.route.paramMap是一个可观察的序列。因此,您存储序列而不是实际返回的值。您希望在收到.subscribe()方法中的数据后存储用户属性

答案 1 :(得分:0)

从html调用:将1替换为您的ID

<a class="btn" href="#/profile/1">

main-routing.module.ts

{
  path: 'profile/:id',
  loadChildren: '../profile/profile.module#ProfileModule',
},

profile.component.ts

constructor(private route: ActivatedRoute) { }

ngOnInit() {
 this.route.params.subscribe( params => console.log(params.id));
}