Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
26
rated 0 times [  32] [ 6]  / answers: 1 / hits: 134024  / 8 Years ago, wed, august 24, 2016, 12:00:00

I have built an app that uses router 3.0.0-beta.1 to switch between app sections. I also use location.go() to emulate the switch between subsections of the same page. I used <base href=/> and a few URL rewrite rules in order to redirect all routes to index.html in case of page refresh. This allows the router to receive the requested subsection as a URL param. Basically I have managed to avoid using the HashLocationStrategy.



routes.ts



export const routes: RouterConfig = [
{
path: '',
redirectTo: '/catalog',
pathMatch: 'full'
},
{
path: 'catalog',
component: CatalogComponent
},
{
path: 'catalog/:topCategory',
component: CatalogComponent
},
{
path: 'summary',
component: SummaryComponent
}
];


If I click on a subsection in the navigation bar 2 things happen:




  • logation.go() updates the URL with the necessary string in order to indicate the current subsection

  • A custom scrollTo() animation scrolls the page at the top of the requested subsection.



If I refresh the page I am using the previously defined route and extract the necessary parameter to restore scroll to the requested subsection.



this._activatedRoute.params
.map(params => params['topCategory'])
.subscribe(topCategory => {
if (typeof topCategory !== 'undefined' &&
topCategory !== null
) {
self.UiState.startArrowWasDismised = true;
self.UiState.selectedTopCategory = topCategory;
}
});


All works fine except when I click the back button. If previous page was a different section, the app router behaves as expected. However if the previous page/url was a subsection, the url changes to the previous one, but nothing happens in the UI. How can I detect if the back button was pressed in order to invoke the scrollTo() function to do it's job again?



Most answers I saw relly on the event onhashchange, but this event does not get fired in my app since I have no hash in the URL afterall...


More From » angular

 Answers
2

I don't know if the other answers are dated, but neither of them worked well for me in Angular 7. What I did was add an Angular event listener by importing it into my component:


import { HostListener } from '@angular/core';

and then listening for popstate on the window object (as Adrian recommended):


  @HostListener('window:popstate', ['$event'])
onPopState(event) {
console.log('Back button pressed');
}

This worked for me.


[#60925] Tuesday, August 23, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cierra

Total Points: 504
Total Questions: 108
Total Answers: 109

Location: Northern Mariana Islands
Member since Fri, Jan 15, 2021
3 Years ago
;