charsi
charsi

Reputation: 3847

Bind button click to service method angular2+

I have a logout method in my auth service. I'm trying to call it from a component, however this does not seem to be working.

template

<a class="dropdown-item" (click)="auth.logout()">Logout</a>

component

import { AuthService } from '../../_services/auth.service';

constructor(
    public auth:AuthService
  ) {}

auth service

  public logout() {
    return this.http.post<any>(this.apiHost+'/users/logout', {})
    .map(() => {
      localStorage.removeItem('currentUser');
      this.router.navigate(['/']);
      this.alertService.warning('You have been logged out.', true)
    })
    .catch(this.handleError);
  }

What am I doing wrong? Do I need to call a local function instead of calling auth directly from the template?

Upvotes: 0

Views: 70

Answers (1)

Pengyy
Pengyy

Reputation: 38171

You can returning an Observable from logout function. But calling this function don't means subscribe from the Observable.

Try to add subscribe() to subscribe it.

public logout() {
  return this.http.post<any>(this.apiHost+'/users/logout', {})
    .map(() => {
      localStorage.removeItem('currentUser');
      this.router.navigate(['/']);
      this.alertService.warning('You have been logged out.', true)
    })
    .catch(this.handleError)
    .subscribe();
}

Upvotes: 2

Related Questions