Observerable + nzModal + CanDeactivate
我们这里的离开的逻辑是,如果没有编辑过内容,就直接离开。如果有编辑过内容就询问是否需要离开。
首先创建QuoteFormCanDeactivate.ts文件:
import {Injectable} from '@angular/core';
import {CanDeactivate} from '@angular/router';
import {QuoteFormComponent} from './quote-form.component';
import {Observable} from 'rxjs';
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
isFormDirty:() => boolean;
}
@Injectable()
export class QuoteFormCanDeactiveate implements CanDeactivate<CanComponentDeactivate>{
canDeactivate(component:QuoteFormComponent):Observable<boolean>|boolean{
if(component.isFormDirty()){
return component.canDeactivate();
}else{
return true;
}
}
}
然后在routing文件配置路由守卫:
{path:"createquote",component:QuoteFormComponent,canDeactivate:[QuoteFormCanDeactiveate]},
我们在QuoteFormComponent中实现
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
isFormDirty:() => boolean;
这两个方法。
quote-form.component.html:
<nz-modal [(nzVisible)]="cdmVisible" nzTitle="确认要离开这个页面吗?" (nzOnCancel)="cancelDeactivateHandler()" (nzOnOk)="deactivateHandler()">
<div>这个页面有未提交的的信息,如果离开页面将丢失所有未提交的信息。确认要离开这个页面吗?</div>
</nz-modal>
quote-form.component.ts
private deactivateObservable : Observable<boolean>;
private deactivateObser : Observer<boolean>;
ngOnInit(){
....
this.deactivateObservable = new Observable<boolean>(observer=>{
this.cdmVisible = true;
this.deactivateObser = observer;
});
.....
}
isFormDirty():boolean{
return this.baseForm.getFormIsDirty();
}
canDeactivate():Observable<boolean> | boolean{
return this.deactivateObservable;
}
cancelDeactivateHandler(){
this.cdmVisible = false;
this.deactivateObser.next(false);
}
deactivateHandler(){
this.deactivateObser.next(true);
}
如果form没有被编辑过,那么跳转就可以直接跳转。
如果有编辑过,就会弹出modal框,询问用户是否确认要跳转了。用户确认后可以跳转,如果用户点取消,那么跳转也会被取消。