Repository navigation
Description
🚀 feature request
Relevant Package
This feature request is for @angular/router
Disclaimer
This feature request can be broken down to several separate issues (bugs and FRs) but I've decided to create one issue to describe my actual use case, problems I have encountered, ideal solution I'd like to have and workaround I came up with.
Use case
I'm working on web site for reading books. I have some "reader" page with infinite scroll that loads next chapter when user scrolls near to of a page. When some chapter enters view-port, I change browser URL to this chapter without triggering navigation (using Location.replaceState).
If users scroll to some next chapter and then reload page or go back/forward in history, they lost scroll position, because saved scroll position (on page with several chapters) is greater then reloaded page length (on page with only "last" chapter)
The idea was to use history.state to save scroll position relative to current chapter top.
Problems
Saving position was pretty straightforward, because Location.replaceState method already has state property. But restoring this state is a pain.
Thanks to #27198 router already knows something about history state, current design/implementation isn't enough do described use case. I didn't figure out why we need both NavigationStart.restoredState and NavigationExtras.state, but despite similar description, they are not the same.
Router itself lacks public method that behaves like Location.replaceState (#24617), and any "outside" changes to history.state are not available as NavigationExtras.state of Router.getCurrentNavigation(), but only available as NavigationStart.restoredState. There is private setBrowserUrl method, that can be used for public implementation.
NavigationStart.restoredState of initial page load can't be reached inside component that is responsible for text rendering (i.e. in the place, which knows chapter top offset, where we need to add saved scroll position), because initial NavigationStart is fired before any component (except of AppComponent) is created. And there is no way to get this value otherwise, except of catching it in AppComponent and saving in some service.
Buy the way workaround from #27198 (comment) to pass NavigationStart.restoredState as NavigationExtras.state doesn't work (any more?) because of resetting currentNavigation here in case of "redirect during NavigationStart".
And even if we can get NavigationStart.restoredState in such hackish way, there is no sense to do this, because of bug. We don't get load any stored state from history in initial navigation (see null in line 951 called from line 778)
Actually we don't even have a way to get this initial state, because all classes on the way from Location, through LocationStrategy, PathLocationStrategy, PlatformLocation, BrowserPlatformLocation up to History lacks an abstraction to get current state.
Hopefully we still can access window.history.state directly. But again, we cann't do it in the component code, because before we create component, router already resets saves history.state with {navigationId:1}. So I still need to write some hackish way to store this value somewhere before first ActivationStart event.
Describe the solution you'd like
I'd like to have a way to straightforwardly call something on router to replace current state and than be able to get this state in Scroll router event. I want this state to be persistently saved even after page reload to moving back/forward outside of angular application.
I don't really care how it will be implemented internally, but just fixing problems above should be enough.
Router should have it's own replaceState (or something) method, that encapsulate any logic around Location.replaceState to handle navigationId or any other possible future angular-specific internal structure of history.state (#27607) and also to provide state as NavigationExtras.state instead of NavigationStart.restoredState.
Describe alternatives you've considered
This section is mostly for someone looking for solution for exactly my use case.
Workaround I came up with consists of two parts.
First - I use resolver to get saved data directly from window.history.state.
Second - because of the same reason I can get data on initial page load - I receive wrong data on navigating away to another chapter. What do I mean? Consider following use case:
- Initial page load without history.
- No data in history -> no scrolling to position.
- Scroll a bit, position is saved to history.
- Reload page.
- Router will rewrite history only on ActivationStart, so we get correct data in resolver.
- There is data from resolver -> scroll to saved position.
- Scroll a bit, position is saved to history.
- Navigate to another chapter directly (there is contents feature in my app).
- Router will rewrite history only on ActivationStart, so we get incorrect data of previous chapter in resolver.
- There is data from resolver -> we scroll to incorrect saved position of previous chapter.
To workaround this problem, I save chapter id together with scroll position, so I can check is this data is relevant.
Final code looks something like this:
progress-resolver.service.ts:
import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from "@angular/common";
import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from "@angular/router";
interface Progress {
scroll: number,
chapterId: number,
}
@Injectable({
providedIn: 'root'
})
export class ProgressResolverService implements Resolve<Progress | null> {
constructor(@Inject(PLATFORM_ID) private platformId: Object) {
}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Progress | null {
if (isPlatformBrowser(this.platformId) && window && window.history && window.history.state && window.history.state.progress) {
return {
scroll: window.history.state.scroll,
chapterId: window.history.state.chapterId,
};
}
return null;
}
}chapter-text.component.ts:
import { AfterViewInit, Component, ElementRef, Input, OnDestroy, ViewChild } from '@angular/core';
import { OnScrollService } from "../on-scroll/on-scroll.service";
import { ActivatedRoute } from "@angular/router";
import { Location, ViewportScroller } from "@angular/common";
import { debounceTime, filter, map } from "rxjs/operators";
import { Subscription } from "rxjs";
@Component({
selector: 'app-chapter-text',
templateUrl: './chapter-text.component.html',
styleUrls: ['./chapter-text.component.scss']
})
export class ChapterTextComponent implements OnDestroy, AfterViewInit {
@Input() chapter: any;
private progressSub: Subscription;
private subscription: Subscription;
private position: { top: number; height: number };
constructor(
private elem: ElementRef,
private route: ActivatedRoute,
private onScroll: OnScrollService,
private location: Location,
private viewportScroller: ViewportScroller,
) {
}
ngAfterViewInit() {
this.position = {
top: this.elem.nativeElement.offsetTop,
height: this.elem.nativeElement.offsetHeight
};
this.subscribe();
}
subscribe() {
this.subscription = this.onScroll.scroll.pipe(
filter(scroll => this.position.top < scroll && scroll < this.position.top + this.position.height),
debounceTime(100),
).subscribe(scroll => this.location.replaceState(this.chapter.url, undefined, {
...window.history.state,
scroll: scroll - this.position.top,
chapterId: this.chapter.chapterId
}));
this.progressSub = this.route.data.pipe(
map(data => data.progress),
filter(progress => progress && this.chapter.chapterId == progress.chapterId),
map(progress => progress.scroll),
).subscribe(scroll => this.viewportScroller.scrollToPosition([0, this.position.top + scroll]));
}
ngOnDestroy() {
this.subscription.unsubscribe();
this.progressSub.unsubscribe();
}
}
Activity
samogot commentedon Feb 24, 2019
@jasonaden, please take a look at this feature request. As far as I can see, you are the right person, who works with this area.
colmben commentedon Mar 28, 2019
I am currently trying to implement a reasonable back button solution that would also allow some state manipulation in-page. The current way state and popstates are handled is very...peculiar!
As this request says, the navigation process now has the ability to set state. Instead of just popping the stored state, location.back() actually creates a new navigation with a restoredState property in the NavigationStart event. Why?
If you change the state with location.replaceState(), location.back wouldn't even find that state to restore, unless you also merge in the (correct? Not sure it needs to be the actual right number) navigationId. Why does it do this?
What I was expecting to find when I saw these changes was an Angular implementation of the History API , which allows any arbitrary state to be placed in history and that state to be immediately available on a pop. Both Location and Router are using names that seem to be related to the History API (replaceState, back etc) but they aren't doing what you would expect from a History API compliant process. Why are we complicating the thing with navigation IDs and restored states? It feels like Location and Router are at cross purposes here and one or the other should properly implement the History API to allow intuitive state management over pops.
jasonaden commentedon Apr 4, 2019
Thanks for the issue. I agree, we need much better APIs for dealing with
history.state. I've got some ongoing work that might help with your use cases. But I wouldn't mind having a further discussion.If you can ping me on Twitter @jasonaden1 we could set up a time to discuss. I would like to see if what I'm currently implementing would end up working for your needs.
samogot commentedon Apr 8, 2019
Sorry, I don't use twitter :)
angular-robot commentedon Jun 4, 2021
Just a heads up that we kicked off a community voting process for your feature request. There are 20 days until the voting process ends.
Find more details about Angular's feature request process in our documentation.
colmben commentedon Jun 4, 2021
Just FYI for the 22 people who thumbs-up'ed the +1 comment, the angular voting process requires a thumbs-up on the first post, the one describing the feature request. This is currently sitting at 7 thumbs-up and requires 20 to be considered.
anishmgoyal commentedon Aug 10, 2021
+1
When reloading the page, state's lost. Going forward or back from the page after reload shows that OTHER pages retain their state, but the initially loaded page does not.
After checking in the constructor for the app component, the value is definitely present - it's just that, for the first page, the router is ignoring it.
cyraid commentedon Aug 17, 2022
My use case is different, and it was kinda difficult to even find this github issue. There are probably others out there that face this issue and have to do workarounds. I use location.go() and try to store state without using navigate. I store the state, but when I listen for window:popstate event, the state just holds the navigationId, not the data I put into it. Is there not a way to get the state I put in, using a navigationId? Or better yet, don't erase my state data I put in? :)
jksware commentedon Aug 30, 2022
For anyone with the same issue, I found a workaround that might suit you (although with a compromise, see at the end):
onSameUrlNavigationtoreload.The compromise is that this method is effectively reprocessing the URL, as noted by the comments in the code for
onSameUrlNavigation:robmv commentedon Sep 15, 2022
I wrote a workaround using a service. It listen for
NavigationStarttriggered by apopstateand store the nativehistory.statebefore Angular touches it. Some top level component must inject it in order to not lose states before it is used down the component hierarchy.I hope this helps until Angular has better support for it.
nebkat commentedon Nov 10, 2022
I think a lot of this thread has lost focus from the core problem:
Goal
The goal is to allow the current state to be modified after a page has been loaded, i.e. to reflect user interactions. This is essential to maintain intuitive forward/back navigation.
History.replaceState()provides a way to achieve this natively.Issue
The issue is that the Angular Router uses
history.statefor it's own internal functionality and unintentionally interferes withhistory.stateafterpopstateevents (forward/back events).Since #27198 the router allows a
stateto be passed when navigating, but there is no clean way for the app to modify the state on the current page after navigation. As originally suggested by @samogot, there should be aRouter.replaceState()method to mirrorHistory.replaceState()without URL changes.There is also a bug that causes the router to discard the state if the internal fields added by the router are not present when forward/back navigation occurs. This means that if the user manually calls History.replaceState(), the state will later be overwritten when returning to the page.
This bug is not a regression but rather the router was never built to handle app states and it is an unintended consequence of some very old code.
Workaround
There is currently a very simple workaround that appears to fix the problem entirely, but it is really just a hack to patch the bug in the router.
Solution
Router.replaceState()method that allows the app to alter the state on a page without affecting router internal operation. TODOrestoredStatefield. Router: Deprecate or removenavigationIdinhistory.state#27607 closed as completed?I have done far too much digging to discard this post, hopefully it will help in making future decisions.
Short History
2016
history.pushState()was used by the router,nullwas always provided as the state.2016
popstate2018
history.stateto storenavigationIdand then populatesNavigationStart.restoredStatewith it.restoredStateseems completely unnecessary at this point?navigationIdfrom state is introduced which later gets misinterpreted.2019
history.statewhen navigating #27198 allows state to be passed withRouter.navigate()navigationIdextract logic to also include the entire state object, but still only ifnavigationIdis present.history.state, and popular StackOverflow questions confirm the same.popstatethe state is reset - only therestoredStateis somewhat handled.2020
navigationIdbeing present.Long History
We start with eb2ceff way back in 2016.
The router uses
history.pushState()andhistory.replaceState()to change the URL displayed in the browser without refreshing the page.nullis always passed as thestateparameter, as the router does not still make any use of the state.When the browser forward/back buttons are pressed (or
location.forward()/location.back()) are used, apopstateevent is emitted. The router listens for this in order to handle the necessary routing changes.Previously, when the router detected a
popstateevent,skipLocationChangewould be used to avoid further altering the state withhistory.replaceState()within the router, as there was no need for this.In order to solve #13491,
skipLocationChangeis disabled forpopstate/hashchangeevent routing. I am not sure if this was the intended result of the commit, but from this point on it seems anypopstateeven will causestateto be set tonulldue to the forced location reset.Next there is af2c0b3 in 2018.
This commit adds
navigationTriggerandrestoredStateto theNavigationStartevent.navigationTriggeris a useful addition to allow differentiating between imperative andpopstatechanges. However,restoredStateseems entirely redundant:angular/packages/router/src/events.ts
Lines 55 to 62 in af2c0b3
angular/packages/router/src/events.ts
Lines 64 to 76 in af2c0b3
navigationIdis an internal field used by the router and to my knowledge is not meaningful outside of the router. The comment suggests that checking for its presence would indicate if apopstatetriggered the navigation, but why do this when it is already evident fromnavigationTrigger?In this commit it appears the addition of
navigationIdtostatewas solely for the purposes of populatingrestoredState, which as per the above should be unnecessary, so I am totally confused as to why it was done. #27607 seems to discuss this.The
popstatehandling code is made to handle the requirements ofrestoredState- which complicates things later:angular/packages/router/src/router.ts
Lines 312 to 320 in af2c0b3
Line 315 just extracts the
navigationIdfrom the state and creates a new object. Whether it is present will solely depend on whether the popped state was originally navigated to by the router or manually by the app with apushStateorreplaceState, and not in line with what the documentation described forrestoredStateabove.Later on #27198 introduces the ability to pass a state during navigation, and it appends the
navigationIdfield as before.A commit from the PR, f7ef94a deals with the
popstatestate handling code slightly differently:angular/packages/router/src/router.ts
Lines 684 to 686 in f7ef94a
The purpose here is probably to maintain the behavior of
restoredStatebeingnullifnavigationIdis not present - but now thatrestoredStatecontains the entire state it is even more unclear why we would want to do this.At this time, the state is still being force reset after every
popstate.Finally in df76a20, a partial fix is made to allow the state to be maintained using the
extras.stateparameter.It continues to discard the state unless
navigationIdis present.fix(router): restore 'history.state' on popstate even if navigationId…
atscott commentedon Nov 11, 2022
@nebkat Appreciate the detailed research here. I don't have the full history either, but I've discovered information that I believe to be true after inheriting ownership of the Router code around 2019:
This was probably closed before GitHub's feature that allowed you to close as won't do vs completed. It was closed as “not worth it”. The unfortunate truth is that it is public API and applications do use it (though it’s rare). Removing it would be a pretty big headache.
The navigationId on the history state is used in two places:
The solution for this is certainly up for debate. I don’t know if adding a
replaceStateis necessary. We will be adding anonSameUrlNavigationoption to thenavigatemethod to override the default (which isignore). So you could instead dorouter.navigate([], {state: newState, onSameUrlNavigation: ‘reload’});fix(router): restore 'history.state' on popstate even if navigationId…
fix(router): restore 'history.state' on popstate even if navigationId…
fix(router): restore 'history.state' on popstate even if navigationId…
atscott commentedon Dec 3, 2023
Closing as generally not relevant anymore. @nebkat outlined quite a few changes that improved things since this was reported and contributed #48033 to shore up yet another issue. There are a lot of options now, including the availability of
onSameUrlNavigationin the navigation extras to effectively reload a route with newstate.If there are still specific issue that need to be addressed, please open a new issue and follow the instructions in the issue template that include info on how to create a reproduction using our template.
angular-automatic-lock-bot commentedon Jan 3, 2024
This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.
Read more about our automatic conversation locking policy.
This action has been performed automatically by a bot.