Using callback on a service? Trying to have a log in modal


#1

I’m trying to set up an app that has a login modal pop up if the user is not logged in. Once they log in through the modal, I want it to disappear and the application to continue doing whatever it was the user was trying to do.

I have the log in system working, and I have the modal popping up when they are not logged in, but I am looking for advice on handling the ‘continue doing x’ part.

My app can create events, so say the user goes to create an event:

$scope.submitEventDetails = function(){
console.log("CreateEvent");
eventsFactory.createEvent($scope.createDetails).then($scope.submitNewEventResponse);
}
$scope.submitNewEventResponse = function(res) {
if(res=="Unauthorized") {
    console.log("Unauthorized");
    //go to login
    var confirmPopup = $ionicPopup.confirm({
        title: 'Please Login ',
        template: 'To create an event please login',
        okText: 'Login'
    });
    confirmPopup.then(function(res) {
        if(res) {
           $scope.loginModal.show().then(function(){
            LoggedInService.listen();
            //then set a callback to listen here? Can't get it to work
            });
        } else {
           console.log('You are not sure');
        }
    });
}
else {
    console.log("Authorized");

}
};

So it checks if the user is logged in, if they are not it pops up saying they have to log in, then the login modal appears and “loggedInService.listen” fires, which looks like this

function LoggedInService($rootScope, $scope, CreateEvent){
this.listen = function(callback) {
    console.log("listening");
    $rootScope.$on("loggedIn",callback)

    function callback(){
        console.log("broadcast heard")
        //CreateEvent.$scope.loginModal.hide();
    }

}
};

The callback works fine and once the user is logged in it gets to “Broadcast Heard” I can’t get access to the modal in that callback though I get the error “TypeError: Cannot read property ‘$scope’ of undefined”, and then if I try to inject ‘CreateEvent’ in to the service like so:

LoggedInService.$inject = ['$rootScope', 'CreateEvent'];

I get:

"Error: [$injector:unpr] Unknown provider: CreateEventProvider <- CreateEvent <- LoggedInService"

If I try to create a callback when the app calls LoggedInService.listen() like so:

confirmPopup.then(function(res) {
        if(res) {
           $scope.loginModal.show().then(function(){
            LoggedInService.listen().then(function(){
                console.log("callback")
            });
            });
        } else {
           console.log('You are not sure');
        }
    });

I get this error:

TypeError: Cannot read property 'then' of undefined

Can someone show me how I should be doing this? Can I set up a callback on a service? Can I just call the function straight from the service? Any help would be greatly appreciated, callbacks trip me up a bit! Thanks