5.7: Member Profile

We'll now work on a new part of our page where users can view details about an individual user.

Adding UserService Method

First, let's add a method in our service to get an individual user.

In user.service.ts add the following method to get an individual user:

getUser(id): Observable<User> {
    return this._http
    .get<User>(this.baseUrl + 'users/' + id);
}

Generating MemberDetailComponent

In the root of your SPA project, generate a new component with the following command:

g c members/member-detail --no-spec

Updating the Component

In the newly created member-detail.component.ts, update it to the following:

export class MemberDetailComponent implements OnInit {

  user: User;

  constructor(
    private _userService: UserService,
    private _route: ActivatedRoute) { }

  ngOnInit() {
    this.loadUser();
  }

  loadUser() {
    this._userService.getUser(+this._route.snapshot.params['id'])
      .subscribe((user: User) => {
        this.user = user;
      }, error => {
        console.log('Failed to load user.');
      });
  }

}

In the load user method, we're using ActivatedRoute's snapshot function to get the parameter of the url. This will be the id of the individual user that we need to query our API.

Add the MemberDetailComponent to the Routes Module

In routes.ts, add a path to the MemberDetailComponent:

export const appRoutes: Routes = [
    { path: 'home', component: HomeComponent },
    {
        path: '',
        runGuardsAndResolvers: 'always',
        canActivate: [AuthGuard],
        children: [
            { path: 'members', component: MemberListComponent },
            { path: 'members/:id', component: MemberDetailComponent },        //  <--- Added
            { path: 'messages', component: MessagesComponent },
            { path: 'followers', component: FollowersComponent },
        ]
    },
    { path: '**', redirectTo: 'home', pathMatch: 'full' },
];

A user will access the profile page from the cards, so let's add a router link to our cards.

In member-card.component.html, add a router link to the first button with the fa-user icon:

<ul class="list-inline member-icons animate text-center">
    <li class="list-inline-item">
      <button class="btn btn-primary"
              [routerLink]="['/members/', user.id]"                             <!-- Added -->
              routerLinkActive="router-link-active">                            <!-- Added -->
      <i class="fa fa-user"></i></button></li>
    <li class="list-inline-item"><button class="btn btn-primary"><i class="fa fa-heart"></i></button></li>
    <li class="list-inline-item"><button class="btn btn-primary"><i class="fa fa-envelope"></i></button></li>
</ul>

Last updated