9.3: Following Functionality in Angular

Our backend is handling 'following' the way we'd like. Now, let's get it working in Angular.

Update UserService

In the user.service.ts file, we'll add a new method called followUser():

followUser(id: number, recipientId: number) {
    return this._http.post(this.baseUrl + 'users/' + id + '/follow/' + recipientId, {});
}

Update MemberCardComponent

In the member-card.component.ts file, update it to the following:

export class MemberCardComponent implements OnInit {

  @Input() user: User;

  constructor(private _authService: AuthService,
              private _userService: UserService,
              private _alertifyService: AlertifyService) { }

  ngOnInit() {
  }

  followUser(id: number) {
    this._userService.followUser(this._authService.decodedToken.nameid, id).subscribe(data => {
      this._alertifyService.success('Now following: ' + this.user.knownAs);
    }, error => {
      this._alertifyService.error(error);
    });
  }

}

We're just injecting our services and calling our followUser() method in our UserService. This is similar to what we've done before.

Add Click Event to Template

In member-card.component.html, we'll add a click event that calls our 'followUser()` method to the button that has a heart icon:

<li class="list-inline-item"><button class="btn btn-primary" (click)="followUser(user.id)"><i class="fa fa-heart"></i></button></li>

Following should be working now! Open the browser and try following different users, log in and someone else and try it again. We don't have much indication in our Angular application outside of the Alertify message. But, open up your database and make sure your 'follow events' are being saved correctly.

Try following a user you're already following. You should get an Alertify box popup with an error message from the server.

Last updated