Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

angular8 - How to Stop Subscribbed router event In Angular 8

In-app Navigation cant be stopped without using Guard???

Below is my Sample Code

 constructor(
      private XXXXXService: XXXXXService
  ) {
    this.XXXX.XX_amount = 0;

    this.routerSubscription = this.router.events.subscribe((event: Event) => {
      if (event instanceof NavigationStart) {
          //do something on start activity
          console.log("event instanceof NavigationStart",this.router.events, event)
          if(this.invoiceForm.dirty){ 
            if(window.confirm("WARNING: You have unsaved changes. Press Cancel to go back and save these changes, or OK to lose these changes."))
            { 
            const currentRoute = this.router.routerState;
            console.log("pressed CANCEL NOT OK", this.router.routerState,currentRoute.snapshot.url);
            this.router.navigateByUrl(currentRoute.snapshot.url, { skipLocationChange: false });
          }
          else
          {
            const currentRoute = this.router.routerState;
            // This is some CODE Im Trying,please ignore this
               //event.preventDefault()
            console.log("pressed CANCEL NOT OK", this.router.routerState,currentRoute.snapshot.url);
            this.router.navigateByUrl(currentRoute.snapshot.url, { skipLocationChange: true });
          }
        }
          
      if (event instanceof NavigationError) {
          // Handle error
          console.error(event.error);
      }

      if (event instanceof NavigationEnd) {
          //do something on end activity
          console.log("event instanceof NavigationEnd")
      }
    }
    });
  }

@HostListener('window:beforeunload', ['$event'])
unloadNotification($event: any) {
    if (this.hasUnsavedData()) {
        $event.returnValue =true;
    }
}
hasUnsavedData()
{
  return !this.XXXXForm.dirty
}

ngOnInit() { console.log(this.location.getState());

Irrespective of Windown Confirm result, the page still navigates to differrent page. In-app Navigation cant be stopped.


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

1 Answer

0 votes
by (71.8m points)

Make the action that changes the route, subject to a form check. I use this in a button on-click event that takes the visitor to another page.

Trying something like this.

onBack(): void {
 if (this.checkForm()) {
    // navigate elsewhere
 }
}

checkForm(): boolean {
   if (this.customerForm.touched) {
       return confirm(`Navigate away and lose all your changes?`);
   }
   return true;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...