0

I am trying to expose an angular service property to $scope, to use it in the view my code looks like this

/**API Post SERVICE for user login*/
        function login(username,password){
            return $http.post('/api/login/',{
                   username:username,
                   password:password
            }).then(loginSuccessFn, loginErrorFn);

            function loginSuccessFn(data, status, headers, config){
                Authentication.setAuthenticatedAccount(data.data);

                window.location = '/';
            }
            function loginErrorFn(data, status, headers,config){
                console.error("Epic Failure");
            }
          }

so when the $http method returns error and the function loginErrorFn() is called, the response data to be passed in the view, so I may raise an bootstrap alert

How can i achieve this ?

  • you have to wrap it all in a promise or `Q.deferred` and in your controller do `service().then(res => $scope.data = res))` – Daniel Lizik Jun 15 '16 at 13:46
  • Don't do that. [Learn to use promises the correct way](http://stackoverflow.com/a/23803744/548997). – Lex Jun 15 '16 at 14:00

2 Answers2

0

inject $rootScope inside the service, emit the event in case of success and error

 $rootScope.$emit('httpCall', 'success');
 $rootScope.$emit('httpCall', 'failure');

and handle these event inside the controller

$rootScope.$on('httpCall', function(p){scope.isSuccess = p;})

now you should refer inside your view to your scope variable isSuccess to display an alert.

Karim
  • 8,454
  • 3
  • 25
  • 33
  • can you please elaborate in a more detail way @Karim –  Jun 15 '16 at 13:43
  • I did this and the response is not showing into view but this error : {"name":"errorLogin","targetScope":"$SCOPE","defaultPrevented":false,"currentScope":null} –  Jun 15 '16 at 14:04
  • can you help me out ? –  Jun 15 '16 at 14:46
0

@Karim was right, just something missed there:

when you inject $rootScope inside the service:

 $rootScope.$emit('httpCall', 'success');
 $rootScope.$emit('httpCall', 'failure');

and when you catch it the:

$rootScope.$on('httpCall', function(e,p){scope.isSuccess = p;})

The $rootScope.$on('httpCall', function(e,p){} has two parameteres