2017-02-09 146 views
6

我已经实现了一个CanDeactivate后卫,以避免用户在上传时离开页面和它的作品。问题在于我的信息始终是默认信息(因为浏览器语言,因此在荷兰语中),甚至自己设置信息,仍然显示相同的默认窗口confirm。我想我自己写的消息(其实我有我要显示一个模式,但首先我想看看我的简单的信息只是工作)CanDeactivate确认消息

任何想法可能是什么?我错过了什么吗? 在此先感谢!

这里的代码

卫队。

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);     
     } 
    } 

组件

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; 
    } 
} 
+0

埃尔默发现安德斯这个问题在这里:角2 - 离开页面之前警告的未保存的更改用户](http://stackoverflow.com/questions/35922071/angular-2-warn-user-of-unsaved-我已经看到了这一点,仍然改变前方的离开页/) –

+0

给了我一个默认的消息文本(在荷兰),而不是我的自定义消息....我使用指定的保护从角文档和工作,但有一个bug像[this](https://github.com/angular/angular/issues/10321)..我很努力地完成这项工作,但直到现在还没有成功。 –

回答

7

试图浏览您的角度应用内其他地方时(例如,从导航到http://localhost:4200/#/test1http://localhost:4200/#/test2)将只显示您的自定义消息。这是因为CanDeactivate防护程序仅在您的Angular应用程序中激活通过Angular路由器进行的路线更改。

当从角应用导航离开(例如,从导航到http://localhost:4200/#/test1http://stackoverflow.com,刷新页面,关闭浏览器窗口/标签等)时,windowbeforeunload事件激活(由于@HostListener('window:beforeunload')注释)和自己处理confirm对话框,而不需要CanDeactivate后卫。在这种情况下,Chrome和Firefox会显示自己的待处理更改警告消息。

你可以阅读更多有关beforeunload事件,它是如何工作here。你会在“注意事项”一节中注意到它规定如下:

在Firefox 4及更高版本返回的字符串不会显示给用户。相反,Firefox会显示字符串“此页面要求您确认您要离开 - 您输入的数据可能无法保存。”

Chrome遵循类似的模式,解释为here

IE /边缘似乎仍然提供指定自定义beforeunload消息的能力。这个例子可以看到here

+0

感谢您的回答,炖!我已经阅读过关于beforeunload事件,并且看到使用它时无法自定义消息。我认为我做错了一件事,因为在你的回答中(从你发布的链接中),没有一件是这样提到的......我试图做不可能的=]。至少现在我知道我正走在正确的道路上。再次感谢。 –

+0

@ElmerDantas - 没问题。我现在更新了对另一个问题的回答,以说明这种区别。对困惑感到抱歉。 – stewdebaker