2

The backend of my app uses a rest api that requires the user to login via basic auth. This means every call they make requires them to send the username and password. But I want my app to hide this detail from the user. Yes, they will have a login page where they enter the username and password in, but from then on they should have no idea they're sending the username/password for every backend call.

My question is, how do I save the username/password on the client after the user submits on the login page so it can be used on every rest call thereafter?

This is almost my question, but the difference is

  1. I'm not using a constant like he is
  2. My value can't be initialized at module config time
  3. I'm not sure if this answer is idiomatic

Side Note: I'm sure some people will leave comments saying, "You shouldn't do that!" Fair enough, but that doesn't answer my question. There are other use cases out there where you need to store a value on the client side that can only be initialized after an action. This is what I'd like to learn.

Community
  • 1
  • 1
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356

1 Answers1

7

I would suggest storing the values in a service and injecting that service anywhere that you need the value. At config time, you can set the value to undefined and then you can fill it in whenever the value is available. This also allows you to use $watch to determine when the value is set.

I'd also take a look at the HTTP Auth Interceptor Module for AngularJS.

Here's a rough example that illustrates this concept.

<div ng-app="exampleApp">
    <div ng-controller="controller1">   
        {{ sharedData.someData }}
    </div>
    <div ng-controller="controller2">   
        <button ng-click="sharedData.someData='otherData'">Set Data</button>
    </div>
</div>


angular.module('exampleApp', []).controller('controller1', function(sharedData, $scope){
    $scope.sharedData = sharedData;      
}).controller('controller2', function(sharedData, $scope){
    $scope.sharedData = sharedData;       
}).service('sharedData', function(){
   this.someData = "test";
   return this;
});
Jon7
  • 7,165
  • 2
  • 33
  • 39
  • This is the way I've done it in the past and seemingly the most correct from a design perspective. – Christopher Marshall Aug 12 '13 at 20:00
  • 2
    I believe that's the standard way to share data between controllers. [This video](http://www.youtube.com/watch?v=HXpHV5gWgyk) exemplifies it. It's worth noticing that all data stored in Angular services will be reset if the page reloads. If that's a problem for you, perhaps you need to use something to persist your data, such as `localstorage`. – Michael Benford Aug 12 '13 at 20:06
  • @Jon7 would you mind showing me a snippet of code showing *how* to store the value in the service? AFAIK a service is a function, how do you save state into it? – Daniel Kaplan Aug 12 '13 at 20:12