Elm*_*tas 10 angular2-routing angular
我已经实施了一个CanDeactivate警卫,以避免用户在上传过程中离开页面并且它可以工作.问题是我的消息始终是默认消息(由于浏览器语言而在荷兰语中),甚至自己设置消息,仍然显示相同的默认confirm窗口.我想写自己的消息(实际上我有一个我想要显示的模态,但首先我希望看到我的简单消息工作)
任何想法可能是什么?我错过了什么吗?提前致谢!
这是代码
守护.
import { Injectable, ViewContainerRef } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { DialogService } from '../services';
export interface PendingUpload {
canDeactivate: () => boolean | Observable<boolean>;
}
@Injectable()
export class PendingUploadGuard implements CanDeactivate<PendingUpload> {
constructor(private dialogService: DialogService, private viewContainerRef: ViewContainerRef) { }
canDeactivate(component: PendingUpload): boolean | Observable<boolean> {
return component.canDeactivate()
? true
: confirm("Test custom message");
//dialog I want to use later
//this.dialogService.confirm("modal title", "modal body", this.viewContainerRef);
}
}
Run Code Online (Sandbox Code Playgroud)
零件
import { Component, OnInit, HostListener } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { PendingUpload } from '../../shared/validators/pending-upload.guard';
import './../../rxjs-operators';
@Component({
selector: 'component-selector',
templateUrl: './html',
styleUrls: ['./css']
})
export class ScannerUploadComponent implements OnInit, PendingUpload {
uploading: boolean = false;
constructor() { }
ngOnInit() {
this.uploading = false;
}
@HostListener('window:beforeunload')
canDeactivate(): Observable<boolean> | boolean {
return !this.uploading;
}
}
Run Code Online (Sandbox Code Playgroud)
ste*_*ker 13
只有在尝试在Angular应用程序中的其他位置导航时才会显示您的自定义消息(例如,从http:// localhost:4200 /#/ test1导航到http:// localhost:4200 /#/ test2).这是因为CanDeactivate防护仅在Angular应用程序中激活通过Angular路由器进行的路由更改.
当您离开Angular应用程序时(例如,从http:// localhost:4200 /#/ test1导航到http://stackoverflow.com,刷新页面,关闭浏览器窗口/选项卡等),window beforeunload事件激活(由于@HostListener('window:beforeunload')注释)并confirm自己处理对话,没有CanDeactivate后卫.在这种情况下,Chrome和Firefox会显示自己的待处理更改警告消息.
您可以在此处详细了解该beforeunload活动及其运作方式.您会在"注释"部分中注意到它声明了以下内容:
在Firefox 4及更高版本中,返回的字符串不会显示给用户.相反,Firefox显示字符串"此页面要求您确认要离开 - 您输入的数据可能无法保存."
Chrome遵循类似的模式,在此解释.
IE/Edge似乎仍然提供指定自定义beforeunload消息的功能.这里可以看到一个例子.