在角度7中注销后如何禁用返回按钮

时间:2019-01-31 12:52:56

标签: angular

我的应用程序中有一个登录页面。我要在成功注销后禁用后退按钮,以使用户无法返回。

3 个答案:

答案 0 :(得分:1)

您不能禁用它,只能阻止它。只需检查登录状态,然后将其重定向到特定页面(如果它们已重定向到需要登录的页面)

答案 1 :(得分:1)

您可以添加防护措施来监视并确定用户是否可以访问页面,而不是禁用浏览器的事件。 CanActivate是救世主

  

可以激活接口

     

类可以实现的接口,以决定是否路由   可以被激活。如果所有防护措施都返回true,则导航将继续。   如果任何防护措施返回假,导航将被取消。 From official documentation of Angular

在这里,我要添加一些当前正在使用的代码。希望它有助于理解如何实现。

import { CanActivate, ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router';

import { IdentityService } from './identity.service';

@Injectable()
export class LoginGuard implements CanActivate {

    constructor(private identityService: IdentityService, private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        if (this.identityService.isLoggedIn()) { // determine if the uder is logged in from this method.
            return true;
        }
        this.router.navigate(['/login']);
        return false;
    }
}

将此LoginGuard类添加到您app.module.ts中的提供者中

providers: [{ provide: LoginGuard, useClass: LoginGuard }]

然后在路由中添加canActive来保护它。

{
    path: 'dashboard',
    component: DashboadComponent,
    canActivate: [LoginGuard]
}

答案 2 :(得分:0)

是的,Auth gurad在这里很有用。

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth-service.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService) {

  }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.authService.getisLoggedIn();
  }
}

在app.module.ts中添加身份验证保护

{ path: 'home', component: HomeComponent, canActivate: [AuthGuard] }
{ path: 'logout', component: LogoutComponent , canActivate:[AuthGuard]}

以便注销后我们可以禁用后退按钮

将身份验证保护作为app.module.ts的一部分添加 提供者:[AuthGuard]