× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS
<p>If you need to store the user's data on the Firebase without letting other users have access to it, it's pretty simple: just include the user's uid in the Firebase path. In other words, instead of:</p> <pre><code class="language-javascript">angular.module('myApp') .factory('exercisesResource', function ($firebaseArray) { return $firebaseArray(new Firebase(baseURL + "/exercises")); });</code></pre> <p>You'd have:</p> <pre><code class="language-javascript">angular.module('myApp') .factory('exercisesResource', function ($firebaseArray, UserService) { return $firebaseArray(new Firebase(baseURL + "/users/" + UserService.getUser().uid + "/exercises")); });</code></pre> <p>Notice that we're using the <code>$firebaseArray</code> service from the AngularFire library to help us access a collection inside Firebase.</p> <p>Just be aware that, unless you're storing locally the user's data, everytime you refresh the page you won't have it anymore, so you'll need to redirect the user to the login page. This also creates a problem: if you have a factory like the one above being used inside the current controller, but you just refreshed the page, this means that you don't have a user yet. In other words, <code>UserService.getUser()</code> will return a <code>undefined</code>, which will throw an exception when you try to access its <code>uid</code> property. How do we solve this?</p> <p>One way is to <strong>not</strong> instantiate the Firebase when creating the factory, so you'll have the chance to check the user's data and redirect him to the login page. You may do that check in many places, I'll write it inside the <code>exercisesResource</code> factory only for simplicity.</p> <pre><code class="language-javascript">angular.module('myApp') .factory('exercisesResource', function ($firebaseArray, $state, UserService) { if (UserService.getUser() == null) { $state.go('login') } var db = null; var getDB = function () { if (db == null) { db = $firebaseArray(new Firebase(baseURL + "/users/" + UserService.getUser().uid + "/exercises")); } return db; }; return { getDB: getDB; }; });</code></pre> <p>Another way to do that is to check the user's data <strong>before</strong> you start to load the controllers:</p> <pre><code class="language-javascript">angular.module('myApp') .run(function ($rootScope, $state, UserService){ $rootScope.$on('$locationChangeStart', function (event) { if (UserService.getUser() == null &amp;&amp; $state.current.name != 'login') { event.preventDefault(); $state.go('login'); } }); });</code></pre> <p>This way, the user will be redirected to the login page before any code in the controller, including the dependency injections, are executed.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus