0

i have a singleton typescript class that stores the Login Credentials of a user. I set them on the login Page and go to the next page with my Angular Router.navigate. (without params), on the next page i want to consume my singleton, and it works perfectly, but if Irefresh the page the singleton is undefined? How can i solve this?

This is the error after refreshing:

  • core.js:5980 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'socialSecurityNumber' of undefined TypeError: Cannot read property 'socialSecurityNumber' of undefined

Thanks

Julian L
  • 1
  • 2

2 Answers2

0

If you refresh the page (F5 in the browser) the whole SPA gets bootstrapped again and services created again.

That means that the new instance of the service will not have the user data unless stored in the storage or cookies.

Also check that the service is provided "in root" and not in any module providers array, so there are no copies of it.

Dani P.
  • 1,073
  • 1
  • 10
  • 28
  • Thanks, but can i prevent that in some way? Or should i change my concept? – Julian L Feb 16 '21 at 07:55
  • You should change your implementation to store user data in storage or cookies, so you can retrieve it from the service in case there is a page reload. Using some standard mechanism like OAuth2 is recommended for web security. – Dani P. Feb 16 '21 at 08:25
0

Mostly in this type of scenario's we will store the user login details in browser storages or cookies.

Try to user Browser storages to store the user related details when you are actually going to keep them in service class.

Have look at here to know about browser storages and how can you set them.

After the above implementation, try to check the user credentials on app component loading, found go with regular flow if not redirect to login page.

P.S: You need some design changes for this to implement like you really want user to continue with current session or need him to redirect login page for new session.

Ganesh
  • 5,808
  • 2
  • 21
  • 41