Fix browser unsaved changes with custom guard

This commit is contained in:
Michael Shamoon
2022-08-06 19:30:39 -07:00
parent cdc7a5842e
commit ea52490f6b
7 changed files with 77 additions and 32 deletions

View File

@@ -1,6 +1,6 @@
import { Component } from '@angular/core'
import { Component, HostListener } from '@angular/core'
import { FormControl } from '@angular/forms'
import { ActivatedRoute, Router, Params } from '@angular/router'
import { ActivatedRoute, Router } from '@angular/router'
import { from, Observable } from 'rxjs'
import {
debounceTime,
@@ -23,13 +23,14 @@ import {
} from 'src/app/services/rest/remote-version.service'
import { SettingsService } from 'src/app/services/settings.service'
import { TasksService } from 'src/app/services/tasks.service'
import { ComponentCanDeactivate } from 'src/app/guards/dirty-doc.guard'
@Component({
selector: 'app-app-frame',
templateUrl: './app-frame.component.html',
styleUrls: ['./app-frame.component.scss'],
})
export class AppFrameComponent {
export class AppFrameComponent implements ComponentCanDeactivate {
constructor(
public router: Router,
private activatedRoute: ActivatedRoute,
@@ -64,6 +65,11 @@ export class AppFrameComponent {
return this.openDocumentsService.getOpenDocuments()
}
@HostListener('window:beforeunload')
canDeactivate(): Observable<boolean> | boolean {
return !this.openDocumentsService.hasDirty()
}
searchAutoComplete = (text$: Observable<string>) =>
text$.pipe(
debounceTime(200),

View File

@@ -206,7 +206,7 @@ export class DocumentDetailComponent
this.store.getValue().title !==
this.documentForm.get('title').value
) {
this.openDocumentService.setDirty(doc.id, true)
this.openDocumentService.setDirty(doc, true)
}
},
})
@@ -228,12 +228,15 @@ export class DocumentDetailComponent
this.store.asObservable()
)
return this.isDirty$.pipe(map((dirty) => ({ doc, dirty })))
return this.isDirty$.pipe(
takeUntil(this.unsubscribeNotifier),
map((dirty) => ({ doc, dirty }))
)
})
)
.subscribe({
next: ({ doc, dirty }) => {
this.openDocumentService.setDirty(doc.id, dirty)
this.openDocumentService.setDirty(doc, dirty)
},
error: (error) => {
this.router.navigate(['404'])
@@ -349,7 +352,7 @@ export class DocumentDetailComponent
Object.assign(this.document, doc)
this.title = doc.title
this.documentForm.patchValue(doc)
this.openDocumentService.setDirty(doc.id, false)
this.openDocumentService.setDirty(doc, false)
},
error: () => {
this.router.navigate(['404'])