Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

Angular CanDeactivateGuard onPopState event is not firing properly

I am using canDeactivateGuard to check if the user has made any changes in the input box and if they have made changes then the canDeactivateGuard will trigger the Alert box to the user.

In my application i am having a custom back button as well when the user presses the custom back button the onPopState triggers properly but when the user clicks the browser back button the popstate triggers sometimes and sometimes it doesn't triggers which results in not showing the alert box.

I have checked whether the router events are called when the browser back button is pressed.But whenever the onPopState is not fired then at that time the router events is also not triggered.

Does anyone has faced the issue like this

Here is my canDeactivateGuard

import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { LocationStrategy } from '@angular/common';

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

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
  backButtonClicked = false;
  constructor(public location: LocationStrategy) {
    location.onPopState(() => {
      console.log('location popstate got called', location);
      this.backButtonClicked = true;
      return false;
    });
  }

  canDeactivate(component: CanComponentDeactivate) {
    if (this.backButtonClicked) {
      this.backButtonClicked = false;
      history.pushState(null, null, location.href);
    }
    return component.canDeactivate ? component.canDeactivate() : true;
  }
}

Component where the Guard is invoked

canDeactivate() {
    if (this.bridgeInterfaceForm.dirty) {
      const message = `${this.globalTranslate.getTranslation('SHARED.DISCARD')}`;
      return this.compWindow.confirm(message);
    }
    return true;
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...