如果有任何更改,如何在离开Angular 4页面时提示用户?

时间:2018-04-12 18:39:06

标签: angular typescript primeng

我的Angular4页面中有两个标签(PrimeNg Tabview),其中包含许多输入字段,例如文本框 textareas 下拉列表等我还有一个侧面菜单栏,可以导航到应用程序中的其他页面。我想如果这些输入字段中的数据有任何更改,那么如果用户尝试更改选项卡,或者使用侧面导航到其他页面,则会出现弹出消息(模式或确认框)菜单栏。

我尝试了ngOnDestroy()方法。虽然此方法仅在页面关闭时触发(通过导航到其他页面或移动到下一个选项卡页面)但是它不允许您在方法中显示模态/确认框,因为它在销毁生命周期钩子上

请帮助我确定实际的事件,如果页面/表单中的任何输入字段中有更改,我可以使用确认框提示用户。

@surjit建议:

我-guard.service.ts

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

@Injectable()
export class CreateRequestGuardService implements CanDeactivate<CanComponentDeactivate> {
    canDeactivate(component: CanComponentDeactivate) {
        let vDeactivate = component.CanDeactivate ? component.CanDeactivate() : true;
        return vDeactivate;
    }   
}

my-component.ts

import { CreateRequestGuardService } from './my-guard.service';

canDeactivate(): Observable<boolean> | boolean {
    console.log('I am moving away!');
    if (!this.isSaved) {
        const confirmation = window.confirm('Are you sure?');
        return Observable.of(confirmation);
    }
    else{
        return true;
    }
}

my-router.ts

import { CreateRequestGuardService } from './my-guard.service';

const allRoutes: Routes = [
   { path: 'save', component: my-component, canDeactivate: [MyGuardService]},
   { path ....},
   ..
]

1 个答案:

答案 0 :(得分:2)

在要保护的组件路径中使用CanDeactivate防护

阅读CanDeactivate了解更多信息

更新:这是我的伪代码。它没有经过测试

我-guard.service.ts:

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

@Injectable()
export class CreateRequestGuardService implements CanDeactivate<CanComponentDeactivate> {
    canDeactivate(component: CanComponentDeactivate, 
                  currentRoute: ActivatedRouteSnapshot, 
                  currentState: RouterStateSnapshot, 
                  nextState?: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        return component.canDeactivate(); //the function will be called on the component, that's why we'll implement the function on the component.
    }   
}

我-router.ts:

import { CreateRequestGuardService } from './my-guard.service'; //the class name in my-guard.service.ts

const allRoutes: Routes = [
   { path: 'save', component: myComponent, canDeactivate: [CreateRequestGuardService]},
   { path ....},
   ..
]

我-component.ts

import { CreateRequestGuardService } from './my-guard.service';

export class myComponent implements CanComponentDeactivate { //implements the interface created on the guard service

    /*
        your component data
    */
    //implementation of canDeactivate
    canDeactivate(): Observable<boolean> | Promise<boolean> | boolean {
        if(form_is_edited && not_saved){
            return confirm("Discard Changes?");
        }
        else
            return true;
    }
}

注意:也不要忘记将保护服务(类)添加到providers文件中的app.module.ts数组。