WKFY
WKFY

Reputation: 84

history.pushState on sub pages in an Angular.js application

I have a blank Angular.js 6 application that uses PathLocationStrategy for routing, and when on a subroute (e.g. /test) and executing the following:

history.pushState({}, '', '#abc');
window.dispatchEvent(new HashChangeEvent('hashchange'));

I would expect the URL to be changed to /test#abc but instead changes the page and URL to the home page (/#abc).

This can be fixed by pretending with the base URL, for example:

history.pushState({}, '', (new URL(window.location.href)).pathname + '#abc');

Unfortunately, I don't have control over the history.pushState command in this case as it's executed externally from ads.

I also tried this in a new Angular 15 application, where similarly the URL updates to /#abc instead of /test#abc but the page didn't change. However, in for example a new Nuxt.js app, it behaves as expected and stays on the test page and the URL becomes /test#abc. So it seems to be perhaps related to Angular.js.

Does anyone know how I can configure my Angular application so it stays on sub-pages when executing:

history.pushState({}, '', '#abc');
window.dispatchEvent(new HashChangeEvent('hashchange'));

Thanks!

Upvotes: 0

Views: 126

Answers (1)

WKFY
WKFY

Reputation: 84

Fixed it by doing the following:

  • Removed the <base href="/"> element in file src/index.html
  • Added provider { provide: APP_BASE_HREF, useValue: '/' } in file src/app/app.module.ts
  • Added "deployUrl": "/" to the build configuration in file angular.json

Upvotes: 0

Related Questions