我有这个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>
在auth.service.ts
文件中我有这个方法:
doLogout() {
return new Promise((resolve, reject) => {
if (firebase.auth().currentUser) {
this.afAuth.auth.signOut();
localStorage.setItem('isLoggedIn', 'false');
resolve();
}
else {
reject();
}
});
}
现在如何使用Angular 5中的(click)
调用此方法?谷歌对Angular 5非常沉默。现在,如果我点击退出按钮,我会收到此错误ERROR Error: "Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'logout'
。我怎样才能让它运行该函数,而不是重定位?我以为后台有某种“防止默认”。
我的路线
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]},
];
答案 0 :(得分:1)
您可以使用服务实例
调用方法<a class='nav-link' (click)="svs.doLogout()" routerLink="/logout">Log out</a>
并确保在构造函数
中注入您的服务constructor( public svs: authService) {}
答案 1 :(得分:0)
我最终做的是:
我将方法添加到主app.component.ts
。这样它在应用程序的各个地方都可用。像这样:
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);
});
}
}
然后,在我的HTML模板中,我刚刚这样做了:
<li class='nav-item'>
<a class='nav-link' (click)="logout()" routerLink="/logout">Wyloguj</a>
</li>
它有效。