-
Notifications
You must be signed in to change notification settings - Fork 11
Account Service in Angular Client
chrisK00 edited this page May 21, 2021
·
1 revision
- Services in angular are singletons. Meaning they are perfect for persisting data such as the current logged in user.
- The account service will be used to login, register and also get the current user either by using RxJs pipe and take(1) or with the async pipe. Using either of theese 2 options allows our app to automatically unsubscribe.
- The service will also be used to set the current user in case for example the user visits the page a couple of hours later causing a refresh, that means our currentUser field will be empty, thats why we have the setCurrentUser method. We can get the user from localstorage as long as its not cleared.
-
private currentUser = new ReplaySubject<User>(1);
: A subject is a type of Observable that can have many subscribers, in this case we are using a replay subject which has a set length like a c# array and "replays" its old value to new subscribers -
currentUser$ = this.currentUser.asObservable();
: Since the subject is private we cant actually get the user from somewhere else. Think of properties in C#, the subject is our backing field which holds the actual value, meanwhile the observable allows us to get the value. In this case its read-only. Some very easy encapsulation!
- We get a user back from our api, so before sending the user back to the caller we want to set the user in localstorage to persist the data even if the user refresh the site and also inside our subject so the app can use the user anywhere in the app.
- We do this using pipe in order to do some operations on the data we get back and then we have to map to go through the data.