CiscoKidx
CiscoKidx

Reputation: 920

Make response from API call accessible from all controllers - angular

I have a controller that takes the user input and post's it to my API and captures the response which happens to be the user data. That's great however I need to access the user data on the dashboard which has a different controller. I can't figure out how to abstract the API call into a service and fetch the response from the dashboard controller. Is there an easier way? The login functionality works perfect however the res.data.user appears inaccessible. My question is how do I make the response accessible from a diffefrent controller?

Controller (signup):

angular.module('app').controller('Signup', function ($scope, $http, toastr, $location, $auth) {

// Submit request to Sails.
$http.post('/api/user/email', {
  email: $scope.signupForm.email.toLowerCase(),
  password: $scope.signupForm.password
})
.then(function onSuccess(res){

  $auth.setToken(res.data.token)
  $location.path('/dashboard')
  $scope.user = res.data.user;

})
})

HTML (dashboard):

<div class="container" ng-show="isAuthenticated()" ng-controller="Dashboard">
<p>License: {{user.license}}</p>
</div>

Upvotes: 1

Views: 173

Answers (1)

deek
deek

Reputation: 1095

Have a factory or service that stores user data to pass around. Inject it in the original

.factory('storeData', function () {

var userData = {}; //it's empty, thats ok

function dataAll () {
return userData;
};

return dataAll;
}


.controller('Signup', function ($scope, $http, toastr, $location, $auth, ***storeData***) {
//remove *** obviously
var importedData = storeData();

// or storeData.dataAll() for some reason OP said this didn't work but it works in my code

$http.post('/api/user/email', {
  email: $scope.signupForm.email.toLowerCase(),
  password: $scope.signupForm.password
})
.then(function onSuccess(res){

  $auth.setToken(res.data.token)
  $location.path('/dashboard')

will modify factory object that was returned to contain res.data.user instead of blank. javascript does not make copies, but instead links back to the original factory object. So changes take place on the factory object.

importedData = res.data.user 


  $scope.user = res.data.user;

})
})

new controller example

.controller('test', function ($scope, storeData) {

console.log(storeData() + 'see if data shows up');
}

Upvotes: 1

Related Questions