noor noor - 3 months ago 22
AngularJS Question

Local Storage Undefined even though it set. Ionic

I am following this example,
https://www.thepolyglotdeveloper.com/2015/02/make-facebook-mobile-app-ionic-framework/

I have declared ng-storage in the app.js file. And :

app.controller('facebookCtrl', ['$cordovaOauth','$scope','$localStorage',function ($cordovaOauth,$scope,oauthService, $localStorage)
{
$scope.login = function()
{
$cordovaOauth.facebook("1234566878", ["email", "user_location","public_profile"]).then(function(result) {
$localStorage.currentUser = result.access_token;

$http.defaults.headers.common.Authorization = 'Bearer ' + $localStorage.currentUser ;
console.log ('acess token is ' + result.access_token)


}, function(error) {
alert("There was a problem signing in! See the console for logs");
console.log(error);
});
};



}]);


I keep getting


cannot set property 'currentUser' of undefined


I have tried initiating it at the start and
$localStorage.set('currentUser', result.access_token);


still not working

Answer

I used this way to define localstorage and it work for me

app.controller('facebookCtrl', ['$cordovaOauth', '$scope', '$localStorage', function($cordovaOauth, $scope, oauthService, $localStorage) {
    $scope.$storage = $localStorage.$default({
        currentUser = null;
    });
    $scope.login = function() {
        $cordovaOauth.facebook("1234566878", ["email", "user_location", "public_profile"]).then(function(result) {
            $scope.$storage.currentUser = result.access_token;

            $http.defaults.headers.common.Authorization = 'Bearer ' + $localStorage.currentUser;
            console.log('acess token is ' + result.access_token)


        }, function(error) {
            alert("There was a problem signing in!  See the console for logs");
            console.log(error);
        });
    };



}]);