无法在CanDeactivate路由器防护

时间:2017-10-11 14:54:20

标签: angular routing angular2-routing state

我为CanDeactivate函数添加了以下路由器保护,以验证未保存的更改,这对我来说很好用

export interface CanComponentDeactivate {       canDeactivate :()=>可观察的|承诺|布尔;     }

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
    constructor( private eventService: EventsService) { }
  canDeactivate(component: CanComponentDeactivate, route?: ActivatedRouteSnapshot,
    currentState?: RouterStateSnapshot,
    nextState?: string) {
      let sub = new Subject();
      if (BaseApiService.callStack.length || UnsavedData.isThereUnSavedData) {
          this.eventService.triggerEvent(CONST.SHOW_DATA_LOSS_MODAL, {
              showDataLossModal: true,
              sub : sub
          });
      }
      return BaseApiService.callStack.length || UnsavedData.isThereUnSavedData ? false : true;
  }
}

但是当我检测到是否有任何未保存的更改时,我会显示一个带有是和否按钮的对话框。

如果用户点击“是”,我必须清除未保存的更改并重定向到用户点击的网址。为此,我必须检查用户想要在CanDeactivate函数上重定向的URL。

nextState?:string 但每次我都明白这一点。

如果我做了任何更改,请纠正我。

1 个答案:

答案 0 :(得分:1)

你需要使用,

nextState?:RouterStateSnapshot

下面的

是接口定义,

interface CanDeactivate<T> { 
  canDeactivate(component: T, 
  currentRoute: ActivatedRouteSnapshot, 
  currentState: RouterStateSnapshot, 
  nextState?: RouterStateSnapshot): Observable<boolean>|Promise<boolean>|boolean
}

检查定义here

<强>更新

检查以下完整示例,

@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>
  <hr />
    <a routerLink="/home" >Home</a>
     <a routerLink="/other" >Other</a>
  <hr />
  <router-outlet></router-outlet>
  `
})
class AppComponent { name = 'Angular'; }

@Component({
  template: `<h1>Home</h1>

  <a routerLink="/other" >Go to Other from Home</a>
  `
})
class HomeComponent {
}

@Component({
  template: `<h1>Other</h1>
  `
})
class OtherComponent {
}

@Injectable()
class CanDeactivateHome implements CanDeactivate<HomeComponent> {
  canDeactivate(
    component: HomeComponent,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState: RouterStateSnapshot
  ): Observable<boolean>|Promise<boolean>|boolean {

   console.log(component);
   console.log(currentRoute);
   console.log(currentState);
   console.log(nextState);

   return true;
  }
}

const appRoutes: Routes = [
  { path: '',   redirectTo: '/home', pathMatch: 'full' },
  { path: 'home',  component: HomeComponent, canDeactivate: [CanDeactivateHome] },
  { path: 'other',  component: OtherComponent }
];

@NgModule({
  imports:      [ BrowserModule, RouterModule.forRoot(appRoutes)],
  declarations: [ AppComponent, HomeComponent, OtherComponent ],
  providers: [CanDeactivateHome],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

选中此Plunker!!

希望这会有所帮助!!