1

I have this HTML

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <div class='container'>
    <ul class="nav navbar-nav">
      <li class='nav-item'>
        <a class='nav-link' routerLink="/">Home</a>
      </li>
      <li class='nav-item'>
        <a class='nav-link' routerLink="/about">About</a>
      </li>
      <li class='nav-item'>
        <a class='nav-link' routerLink="/login">Log in</a>
      </li>
      <li class='nav-item'>
        <a class='nav-link' routerLink="/register">Register</a>
      </li>
      <li class='nav-item'>
        <a class='nav-link' (click)="doLogout()" routerLink="/logout">Log out</a>
      </li>
    </ul>
  </div>
</nav>

In an auth.service.ts file I have this method:

doLogout() {
  return new Promise((resolve, reject) => {
    if (firebase.auth().currentUser) {
      this.afAuth.auth.signOut();
      localStorage.setItem('isLoggedIn', 'false');
      resolve();
    }
    else {
      reject();
    }
  });
}

Now how can I call this method using the (click) in Angular 5? Google is weirdly silent about Angular 5. Right now, if I click the Log out button I get this error ERROR Error: "Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'logout'. How can I get it to do run the function, instead of the relocation? I thought there is some kind of "preventDefault" in the background.

My routes

export const rootRouterConfig: Routes = [
  // {path: '', redirectTo: '', pathMatch: 'full'},
  {path: '', component: HomeComponent},
  {path: 'about', component: AboutComponent},
  {path: 'login', component: LoginComponent, canActivate: [AuthGuard]},
  {path: 'register', component: RegisterComponent, canActivate: [AuthGuard]},
  {path: 'user', component: UserComponent, resolve: {data: UserResolver}},
  // {path: 'tasks', component: TasksComponent, canActivate: [AuthGuard]},
];
5
  • 1
    Running the function is one thing, but you also seem to have a routing problem. Can you post your routing module? Commented May 21, 2018 at 8:35
  • 1
    You don't have a /logout route, which is what the error is telling you Commented May 21, 2018 at 8:42
  • I updated. I'm simply not managing the case. I thought it's just gonna run the function. All would be handled there Commented May 21, 2018 at 8:42
  • 1
    Your doLogout function has nothing to do with routing at the moment. And even if you wanted to handle redirection inside the function, you'd still need to add the route to your routerConfig Commented May 21, 2018 at 8:44
  • Ok I think I kind of get it. Commented May 21, 2018 at 8:44

2 Answers 2

2

You can call method using the service instance

<a class='nav-link' (click)="svs.doLogout()" routerLink="/logout">Log out</a> 

and make sure to inject your service inside constructor

constructor( public svs: authService) {}
Sign up to request clarification or add additional context in comments.

3 Comments

And make sure that you have configured all your routes in a module.
Is it possible to add this to only one component and have it work on every other?
Ok right now, it does redirect me, but it doesn't call the function. My IDE says this: Identifier is not defined. The component declaration, template variable declarations, and element references do not contain such a member. I added public svs: authService to every constructor.
1

What I ended up doing was this:

I added the method to the main app.component.ts. This way it became available everywhere in the app. Like this:

import {Component, ViewEncapsulation} from '@angular/core';
import {AuthService} from './core/auth.service';
import {Router} from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  encapsulation: ViewEncapsulation.None
})

export class AppComponent {
  showLogout: boolean = false;

  constructor(
    public authService: AuthService,
    private router: Router,
  ) {
  }

  checkSession() {
    var checkKey = localStorage.getItem('sessionKey');
    if (checkKey == null) {
      this.showLogout = false; // changed
      console.log('null key: ', checkKey);
    } else {
      this.showLogout = true; // changed
      // this check will only be available once the user is logged in
      console.log('key exist: ', checkKey);
    }
  }

  logout() {
    this.authService.doLogout()
      .then((res) => {
        this.router.navigateByUrl('/login');
      }, (error) => {
        console.log('Logout error', error);
      });
  }
}

Then, in my HTML template I just did this:

<li class='nav-item'>
  <a class='nav-link' (click)="logout()" routerLink="/logout">Wyloguj</a>
</li>

And it works.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.