ब्राउज़र रिफ्रेश के विरूद्ध गार्ड को कवर करने के लिए, खिड़की बंद करना, आदि (देखें इस मुद्दे पर विवरण के लिए गुंटर के जवाब में @ क्रिस्टोफ़ेविडल की टिप्पणी), मुझे @HostListenerआपकी कक्षा के canDeactivateकार्यान्वयन के लिए डेकोरेटर को जोड़ना मददगार लगा है ।beforeunload window इवेंट के । सही तरीके से कॉन्फ़िगर किए जाने पर, यह एक ही समय में इन-ऐप और बाहरी नेविगेशन दोनों के खिलाफ रक्षा करेगा।
उदाहरण के लिए:
घटक:
import { ComponentCanDeactivate } from './pending-changes.guard';
import { HostListener } from '@angular/core';
import { Observable } from 'rxjs/Observable';
export class MyComponent implements ComponentCanDeactivate {
// @HostListener allows us to also guard against browser refresh, close, etc.
@HostListener('window:beforeunload')
canDeactivate(): Observable<boolean> | boolean {
// insert logic to check if there are pending changes here;
// returning true will navigate without confirmation
// returning false will show a confirm dialog before navigating away
}
}
रक्षक:
import { CanDeactivate } from '@angular/router';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
export interface ComponentCanDeactivate {
canDeactivate: () => boolean | Observable<boolean>;
}
@Injectable()
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
// if there are no pending changes, just allow deactivation; else confirm first
return component.canDeactivate() ?
true :
// NOTE: this warning message will only be shown when navigating elsewhere within your angular app;
// when navigating away from your angular app, the browser will show a generic warning message
// see http://stackoverflow.com/a/42207299/7307355
confirm('WARNING: You have unsaved changes. Press Cancel to go back and save these changes, or OK to lose these changes.');
}
}
मार्ग:
import { PendingChangesGuard } from './pending-changes.guard';
import { MyComponent } from './my.component';
import { Routes } from '@angular/router';
export const MY_ROUTES: Routes = [
{ path: '', component: MyComponent, canDeactivate: [PendingChangesGuard] },
];
मापांक:
import { PendingChangesGuard } from './pending-changes.guard';
import { NgModule } from '@angular/core';
@NgModule({
// ...
providers: [PendingChangesGuard],
// ...
})
export class AppModule {}
नोट : जैसा कि @JasperRisseeuw ने बताया, IE और एज beforeunloadइवेंट को अन्य ब्राउज़रों से अलग तरीके से हैंडल करते हैं और falseजब यह beforeunloadइवेंट सक्रिय हो जाता है (जैसे, ब्राउज़र रीफ्रेश, विंडो को बंद करना, आदि) को कन्फर्मेशन डायलॉग में शामिल करेगा । कोणीय ऐप के भीतर नेविगेट करना अप्रभावित है और आपके निर्दिष्ट पुष्टि चेतावनी संदेश को ठीक से दिखाएगा। जिन लोगों को आईई / एज का समर्थन करने की आवश्यकता होती है और falseजब beforeunloadघटना सक्रिय हो जाती है, तो पुष्टिकरण संवाद में एक अधिक विस्तृत संदेश दिखाना / नहीं करना चाहते / चाहती हैं कि वह वर्कअराउंड के लिए @ JasperRisseeuw का उत्तर भी देखना चाहें।