Javascript 请用户在离开组件之前保存数据
我有一个组件父级Javascript 请用户在离开组件之前保存数据,javascript,html,angular,typescript,Javascript,Html,Angular,Typescript,我有一个组件父级应用程序侧栏,它可以有两个不同的子级,具体取决于变量: <app-content-right *ngIf="!componentService.getEditor.inView"></app-content-right> <!-- alternative editors --> <app-labtech-home *ngIf="componentService.getComponentEditor && c
应用程序侧栏
,它可以有两个不同的子级,具体取决于变量:
<app-content-right *ngIf="!componentService.getEditor.inView"></app-content-right>
<!-- alternative editors -->
<app-labtech-home *ngIf="componentService.getComponentEditor && componentService.getEditor.inView"></app-labtech-home>
在app labtech home
组件内部,但它在没有模式的情况下退出,我需要截获退出,并仅在用户接受时执行。我怎样才能做到这一点?谢谢PS:路线不会改变,它是同一页面中的不同组件(实际上是不同的项目) 我的路由模块:
export const routes: Routes = [
{ path: 'login', component: LoginComponent},
{ path: '', component: HomeComponent, canActivate: [AuthGuard],canDeactivate:[BackButtonDeactiveGuard]}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
我想你在找这个: 试着这样做:
- 创建停用GuardService
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs/Observable';
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
@Injectable()
export class DeactivateGuardService implements CanDeactivate<CanComponentDeactivate>{
canDeactivate(component: CanComponentDeactivate) {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
- 当任何用户试图离开表单为脏的页面时,调用服务方法
export class ExampleComponent {
loading: boolean = false;
@ViewChild('exampleForm') exampleForm: NgForm;
canDeactivate(): Observable<boolean> | boolean {
if (this.exampleForm.dirty) {
alert('Discard Unsaved Changes?');
}
return true;
}
}
导出类示例组件{
加载:布尔值=false;
@ViewChild('exampleForm')exampleForm:NgForm;
canDeactivate():可观察的|布尔值{
if(this.exampleForm.dirty){
警报(“放弃未保存的更改?”);
}
返回true;
}
}
路线没有改变,只是同一页中的不同部分对不起,我没有成功地阅读您的问题:(这是相同的路由,包含不同的组件显示路由模块。这里您没有相同的路由,包含不同的组件。男性,我只有一条路由,因为我在页面的右侧有左侧菜单上可单击的所有组件的容器
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'example',
canDeactivate: [DeactivateGuardService],
component: ExampleComponent
}
])
]
export class ExampleComponent {
loading: boolean = false;
@ViewChild('exampleForm') exampleForm: NgForm;
canDeactivate(): Observable<boolean> | boolean {
if (this.exampleForm.dirty) {
alert('Discard Unsaved Changes?');
}
return true;
}
}