Search code examples
angularbrowser-history

LocationStrategy.pushState(state: any, title: string, url: string, queryParams: string) - What is state?


What can I do with the state argument in pushState(state: any, title: string, url: string, queryParams: string) ?

Can I store data ?

Is there any documentation out there that would be more 'detailed' than https://angular.io/api/common/LocationStrategy#pushState ?

<3


Solution

  • This pushState function will ultimately map to the browser's history.pushState function in one way or another. The MDN docs gives a detailed description of how this state property is used:

    The state object is a JavaScript object which is associated with the new history entry created by pushState(). Whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object.

    The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restarts the browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to pushState(), the method will throw an exception. If you need more space than this, you're encouraged to use sessionStorage and/or localStorage.

    (Emphasis mine/OP's).

    The popstate event described here is available in Angular via its Location service. Specifically, you can subscribe to the Location service in order to listen for PopStateEvents, which include a state property containing what you would expect.