I don't think it is a good idea to block the back button. You can use a caching mechanism for the requests so it won't send the request to server every time, but getting the latest response. Please check this example:
const URL = 'https://api.punkapi.com/v2/beers';
@Injectable({
providedIn: 'root'
})
export class HttpService {
public responseCache = new Map();constructor(private http: HttpClient) {}public getBeerList(): Observable<any> {
const beersFromCache = this.responseCache.get(URL);
if (beersFromCache) {
return of(beersFromCache);
}
const response = this.http.get<any>(URL);
response.subscribe(beers => this.responseCache.set(URL, beers));
return response;
}
}
If you still want your solution to block the user from going back, you will need to use Guards in order to cancel the navigation.
@Injectable()
export class MyGuardService implements CanActivate {
constructor(public auth: AuthService, public router: Router) {}
canActivate(): boolean {
return !this.myService.stillDontWantToGoBack()
}}
This will be for all navigations, if you still want only the back, you will need to check if the URL you are going to is the same as previousUrl.
my-service.service.ts
previousUrl: string;
constructor(router: Router) {
router.events
.filter(event => event instanceof NavigationEnd)
.subscribe(e => {
console.log('prev:', this.previousUrl);
this.previousUrl = e.url;
});
}
in my-guard.guard.ts
canActivate(route: ActivatedRouteSnapshot) {
return route.url !== this.myService.previousUrl;
}
References and more info: