User Authentication with Ionic Cloud Auth rxjs/BehaviorSubjectClearly Innovative | Web and Mobile Development

User Authentication with Ionic Cloud Auth - Using rxjs/BehaviorSubject


[ JUST SHOW ME THE CODE: https://github.com/aaronksaunders/Ionic2-Ionic.io-Auth-Example ]


A few weeks ago I was playing with user authentication and tracking down login state when I found a solution using rxjs/BehaviorSubject. I thought it was so cool that I did a simple plunker to show how it could be done. I guess people found it interesting because it was retweeted a few times

So I decided to create a complete project with the functionality in it but this time really use an authentication system on the backend. Since I was targeting the solution to Ionic users, I figured the easiest approach was to use the Ionic.io Auth Services

Setup your application to use the Ionic.io Auth Service for Authentication; I am only touching on the key changes in the application to support the use of rxjs/BehaviorSubject to managing authentication state

Lets Start With The Code

The heavy lifting for this blog post is around managing authentication state in a reactive way using the rxjs/BehaviorSubject and the bulk of that code lives in the auth.ts file of the project.

We will need to import the library and then define the variable holding the current user.

then inside the class we create the property

We us the Ionic.io Service to login a user and when the user is logged in we set the value of the BehaviorSubject using the values from the Ionic User object. See the ionic documentation for additional information https://docs.ionic.io/services/auth/

This is the specific line which is setting the activeUser which will update all of the places that are subscribed to the variable this.activeUser

Inside of the app.component.ts is where the real work is happening, we subscribe to the this.auth.activeUser from the Authentication Service to be notified of a change in status. When the activeUser is updated all subscribers will get notified with the new user

The rest of the application is pretty straight forward implementation of user login with the Ionic.io Authentication Services and that has been covered in the Ionic Documentation.

Please take a look here for the complete source code of the project by clicking the link below:

Simple Ionic2 App Using Ionic.io Auth And rxjs/BehaviorSubject – IonicFramework