(角度2/4/5/6)更改浏览器后退按钮的导航

时间:2019-05-14 08:46:51

标签: angular routing angular6

上一个问题:

如果用户单击浏览器后退按钮,我试图将用户导航到主页(而不是上一页)。

解决方案:

我结合使用了candeactivateguard和hostlistener。请记住在模块文件下的提供程序中声明您的守卫。

deactivate.guard.ts

import { Injectable } from "@angular/core";
import { CanDeactivate } from "@angular/router";

export interface CanComponentDeactivate {
  canDeactivate(): boolean;
}

@Injectable()
export class DeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
  canDeactivate(component: CanComponentDeactivate): boolean {
    return component.canDeactivate();
  }
}

lastpage.component.ts

import { Component, OnInit, Inject, HostListener } from "@angular/core";
export class LastPageComponent implements OnInit {
   disableSuccessNav = false;
   ngOnInit() {}
   constructor()
   //detects browser back button
   @HostListener("window:popstate")
   onPopState() {
     this.disableSuccessNav = true;
   }

   canDeactivate() {
      return !this.disableSuccessNav;
    }

0 个答案:

没有答案