0

I want to create a global function like:

function CheckAuthorization($window)
{
    if($cookieStore.get('token')=='')
        $window.location.href = '/login';
}

and call it everywhere. Is this possible? The above code is not working.

Nikita R.
  • 7,245
  • 3
  • 51
  • 62
Samir Rawat
  • 53
  • 1
  • 2
  • 8
  • This is my service `app.factory('myService', function () { return { CheckAuthorization: function () { if ($cookieStore.get('token') == '') $window.location.href = '/login'; } }; });` call this in controller like this : `app.controller('ContactController', function ($scope, myService) { myService.CheckAuthorization(); $scope.message = "ContactController"; });` but i am getting an error like as – Samir Rawat Aug 26 '16 at 17:19
  • The answer to the link above should work for you. There is a very simple example for creating a service to hold the function or a simple example to add it to the root scope. http://stackoverflow.com/a/15026440/4084574 You should not have any problems adapting this. – mhatch Aug 26 '16 at 17:23
  • @mhatch actually i am getting problem in this line `$window.location.href = '/login';` – Samir Rawat Aug 26 '16 at 17:26
  • Have you tried using Angular `$location`? https://docs.angularjs.org/guide/$location – mhatch Aug 26 '16 at 17:31
  • @mhatch yes its not working and then i used this `$window.location.href = '/login'`.. – Samir Rawat Aug 26 '16 at 17:34
  • Try logging out the contents of `$window.location.href` to see if it matches what you expect? My suspicion might be that it involves the angular single page routing. If you create a plunker I can look at it. – mhatch Aug 26 '16 at 17:38
  • `/login` is just a route to a view. So what you really want to do is change the view, not reload the whole page. – mhatch Aug 26 '16 at 17:42
  • @mhatch i am checking for cookie `if ($cookieStore.get('token') == '')` and if cookie is null then redirect to the login view – Samir Rawat Aug 27 '16 at 08:13

0 Answers0