I want when someone press browser's back button to warn him and if he press ok then i will redirect to Home Component. I use CanDeactivate Guard and i want to change the nextState of CanDeactivateGuard. I tried to change the nextState :
nextState = { root: currentRoute, url: '/' }
but always redirect me to the previous component
can-deactivate-guard.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
@Injectable({
providedIn: 'root'
})
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState?: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
nextState = { root: currentRoute, url: '/' }// try this, but dosen't work
return component.canDeactivate();
}
}
My components code. pressContinue is just a boolean in case someone press continue button for the next component.
canDeactivate() {
if (this.pressContinue) {
return true;
} else {
return confirm('Are you sure?');
}
}
I don't know if it's the best solution but i change the logic on my component to redirect me to homepage and it's working!
canDeactivate() {
if (this.pressContinue) {
return true;
} else {
var resp = confirm('Are you sure?');
if(resp == true)
window.location.href = '';
return false;
}
}