如果未保存项目并显示确认框,Angular 会阻止路由器。但它显示两个模式弹出窗口

问题描述 投票:0回答:1

我尝试阻止路由器并显示确认弹出窗口。它可以工作,但显示两个模式弹出窗口,因为每个条件导航开始点击两次 {

constructor(
    private route: ActivatedRoute,
    private router: Router,
){
const currentRoute = this.router.routerState;
    
    
    router.events.forEach((event:any) =>{
          
      if(event instanceof NavigationStart){
        if(this.paContentId){           
          const modalRef = this.modalService.open(ConfirmPopupComponent, { 
            centered: true,
            modalDialogClass: 'confirm-model custom-modal'
          })
      
          modalRef.componentInstance.displayValue = {
            title: 'Confirm',
            content: 'You have unsaved changes. System will clear all of these data if you switch to another screen. Do you want to proceed?'
          }
          const currentRoute = this.router.routerState;
          this.router.navigateByUrl(currentRoute.snapshot.url, { skipLocationChange: true });
          modalRef.componentInstance.checkConfirm.subscribe((receivedCheck: boolean) => {
            if(receivedCheck) {  
              this.paContentId = '';
              this.router.navigate([event.url])    
            }else{
              
            }
          });
          
        }
      }
     
      
    })
}

如果未保存的项目需要显示弹出窗口,并且我们也在材质 UI 选项卡中使用

javascript angular typescript
1个回答
0
投票

我们需要订阅路由器事件,我们不应该运行for循环,请查看下面的示例代码,如果仍然调用两次,请尝试注释的代码!

import { Component, NgModule } from '@angular/core';
import { Routes, RouterModule, NavigationStart } from '@angular/router';
import { Router, NavigationEnd } from '@angular/router';
import { debounceTime } from 'rxjs/operators';
@Component({
  selector: 'my-app',
  template: `<a routerLink='A'>A</a>
    <a routerLink='B'>B</a>
    <router-outlet></router-outlet>`,
})
export class AppComponent {
  constructor(private router: Router) {}

  ngOnInit() {
    this.router.events
      .pipe
      // debounceTime(250)
      ()
      .subscribe((event) => {
        if (event instanceof NavigationStart) {
          alert('navigation succeeded');
        }
      });
  }
}

@Component({
  selector: 'app-a',
  template: '<h1>A</h1>',
})
export class AComponent {}

@Component({
  selector: 'app-b',
  template: '<h1>B</h1>',
})
export class BComponent {}

const routes: Routes = [
  { path: 'A', component: AComponent },
  { path: 'B', component: BComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class RootRoutingModule {}

Stackblitz 演示

© www.soinside.com 2019 - 2024. All rights reserved.