I saw a similar question created about five years ago, but my question is a little different:
I wrote a breadcrumb for whole app component, as a part of my outermost layout.
In breadcrumb, I used 'location.back()' to make a back button:
<i
*ngIf="this.urlLevels > 1"
nz-icon
nzType="arrow-left"
nzTheme="outline"
(click)="back()"
></i>
import { Location } from '@angular/common';
constructor(private location: Location) {}
back() {
this.location.back();
}
My App Routes like:
{
path: '',
redirectTo: 'blog',
pathMatch: 'full',
},
{
path: 'login',
component: LoginComponent,
},
{
path: '',
canActivateChild: [RouteGuard],
children: [
{
path: 'blog',
component: LayoutComponent, // breadcrumb is a part of this component
children: [
{
path: '',
loadChildren: () => import('src/app/blog/blog.module').then((m) => m. BlogModule),
},
],
data: {
icon: '',
breadcrumb: 'Blog'
},
},
],
},
{
path: '**',
component: NotFoundComponent,
},
The routes of BlogModule like:
{ path: '', redirectTo: 'bloglist', pathMatch: 'full' },
{
path: 'bloglist',
component: BlogListComponent,
data: {
breadcrumb: '',
},
},
{
path: 'createblog',
component: CreateBlogComponent,
data: {
breadcrumb: 'CreateBlog',
},
canDeactivate: [BeforeLeaveGuard],
},
The BeforeLeaveGuard:
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs';
import { CreateBlogComponent } from './create-blog.component';
@Injectable()
export class BeforeLeaveGuard implements CanDeactivate< CreateBlogComponent > {
canDeactivate(component: CreateBlogComponent): Observable<boolean> | boolean {
component.openDialog(); // I open a leave-confirm dialog here
return component.confirmed; // result of confirm dialog
}
}
The question is : When I hit the back button, my CanDeactivate doesn't work, my page changed just like there isn't a guard.
I saw two methods of router in http://angular.io/api/router/Router, they are: initialNavigation(), setUpLocationChangeListener()
It seems they can help me to solve my problem. I tried to use them in my BlogModule, but they both didn't work (nothing happened, my page still changed successfully, ignored all my settings).
What is the problem? T_T
I need your help.