简体   繁体   中英

AngularJS - Redirect after login not working

After a user successfully logs in i would like the page to redirect to the homepage. My code currently looks like:

function MainCtrl(user, auth) {
  var self = this;

  function handleRequest(res) {
    var token = res.data ? res.data.token : null;
    if(token) { $location.path('/'); }
    self.message = res.data.message;
  }

  self.login = function() {
    user.login(self.username, self.password)
      .then(handleRequest, handleRequest)
  }

}

Why does the line $location.path('/'); not work, is that where i should actually have the redirect?

And the route config part:

.config(function($routeProvider){
  $routeProvider.when("/",
    {
      templateUrl: "views/home.html"
    }
  )
  .when("/login",
    {
      templateUrl: "views/login.html"
    }
  )
  .when("/register",
    {
      templateUrl: "views/register.html"
    }
  );
})

Thanks.

You forget to inject $location in your controller

Try like this

function MainCtrl(user, auth,$location) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM