My Angular Dashboard Template part 2: BehaviourSubject and Destructuring

The Hangry Coder
3 min readDec 3, 2018

--

If you haven’t read my previous post, then I suggest you do that first:

My previous article was so long, I decided to write another article with some other features/updates I’ve implemented in my template.

You can start with my template right away, I’ve shared it on my Github:

Update!

I’ve written a follow up article about CRUD on this project:

Auth state with Behaviour Subject

When I wrote my previous article, I used Subjects() to emmit a login (onLogin = new Subject<any>();) and logout event (onLogout = new Subject<any>();).

The app.component.ts would then register on those events and set a variable in the component (loggedIn) and do some logic on it (and displaying the correct router-link).

Now I’ve simplified this by using RxJS Behaviour Subject. The behaviour subject is a Subject() with some extra’s:
- you can set an initial value
- every value you emmit, it get’s saved in the Behaviour Subject

By setting an initial value, a subscriber wil already have a value when it subscribes to this observable. For example in my auth service file :

I’ve created a BehaviourSubject with a boolean. Now, even without doing anything with this Observable, an observer can subscribe to it and already will have a value: false .

Now in my previous post I used the 2 old Subjects to listen for a login/logout event and then set the loggedIn variable so I can use this in my template. But now with the BehaviourSubject I can use it as an observable in my template.

First I need to have a reference to my BehaviourSubject:

And then I can use it in my template:

Notice the async pipe. This will subscribe to the loggedIn$ from the template. A big advantages is also that you don’t have to unsubscribe manually. And every time I emmit a new value in my auth service, all subscribers will get the new value:

Destructuring login parameters

In my auth service file, I have a login function that will connect to the server to do the actual login. This function has 2 parameters:

  • username (string)
  • password (string)

Then from my login.component.ts I would call it like this:

Nothing fancy right? But TypeScript has a feature called destructure. With this I can now just send an object (this.loginForm.value) as parameter, but on the recieving side, I’ll just use what I need from that object:

So in a nutshell, login({ username , password }) will accept an object, but we only use the username and password keys.

So that’s it! I need food!!!!

You can find me on :
- linkedin : https://www.linkedin.com/in/fransjoleihitu/
- GitHub : https://github.com/fransyozef/
- Instagram : https://www.instagram.com/thehangrycoder/
- Twitter: https://twitter.com/thehangrycoder

--

--