CanDeactivate Guard 重定向到主页

CanDeactivateGuard redirect to the home page

我想要当有人按下浏览器的后退按钮时警告他,如果他按下确定,那么我将重定向到主页组件。我使用 CanDeactivate Guard,我想更改 CanDeactivateGuard 的 nextState。我试图改变 nextState :

nextState = { root: currentRoute, url: '/' }

但总是将我重定向到上一个组件

可以-停用-guard.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

export interface CanComponentDeactivate {
   canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}

 @Injectable({
  providedIn: 'root'
 })
 export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {

 canDeactivate(component: CanComponentDeactivate,
 currentRoute: ActivatedRouteSnapshot,
 currentState: RouterStateSnapshot,
 nextState?: RouterStateSnapshot
 ): Observable<boolean> | Promise<boolean> | boolean {

 nextState = { root: currentRoute, url: '/' }// try this, but dosen't work
 return component.canDeactivate();
 }
}

我的组件代码。 pressContinue 只是一个布尔值,以防有人按下下一个组件的继续按钮。

  canDeactivate() {
  if (this.pressContinue) {
     return true;
   } else {
     return confirm('Are you sure?');
   }
  }

希望这对您有所帮助...

app.service

 clickedBackButton = false;
 constructor() { }

 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
     if(this.clickedBackButton) {
       this.clickedBackButton = false;
       return false;
     }
   return true;
  }

app.routing.module

const routes: Routes = [ 

  {path: '', component: HomeComponent, canActivate: [AppService]},
  {path: 'about', component: AboutComponent, canActivate: [AppService]}
];

app.component.ts

constructor(
private location: PlatformLocation,
private appService: AppService) {}

ngOnInit() {    
  this.location.onPopState(() => {
    let conf = confirm('Please confirm');
    if(conf) {
      this.appService.clickedBackButton = false;
      return;
    } 
    this.appService.clickedBackButton = true;
  });
}

app.component.html

<div class="container">
<div class="row">
    <div class="col-4">
        <button class="btn btn-success" style="margin-right: 5px;" [routerLink]="['/']" routerLinkActive="router-link-active" >Home</button>
        <button class="btn btn-primary" [routerLink]="['/about']" routerLinkActive="router-link-active" >About</button>
    </div>
</div>
<router-outlet></router-outlet>

我不知道这是否是最佳解决方案,但我更改了组件上的逻辑以将我重定向到主页并且它正在运行!

canDeactivate() {
if (this.pressContinue) {
  return true;
 } else {
  var resp = confirm('Are you sure?');

  if(resp == true)
  window.location.href = '';

  return false;
 }
}