Thịnh Phạm
Thịnh Phạm

Reputation: 2663

Protect routes and redirect user based on some conditions with Angular ui-router

The scenario is:

For some routes in my app, I want to force user to complete their profile first.

There are a few ways to achieve that:

  1. Redirect inside the user resolve (where we load the user data)
  2. Listen to $stateChangeStart event, load user from server, check if profile is complete

With method 1, is it possible to reuse the user resolve for other routes (given the fact that user resolve pending on auth resolve)?

With method 2, I feel like this method is bug-prone and hard to keep track.

Is there any best practice to this problem?

Upvotes: 0

Views: 527

Answers (1)

Sravan
Sravan

Reputation: 18647

You can use service in the resolve to reduce the code in the routes and reuse the resolve function

Here is an example implementation of it.

$stateProvider
  .state('inbox', {
    ...
    resolve: {
      profile: function (UserService) {
        return UserService.getUser();
      },
    }
  })
  .state('dashboard', {
    ...
    resolve: {
      profile: function (UserService) {
        return UserService.getUser();
      },
    }
  });

Your controller can be,

angular
  .module('app')
  .controller('DashboardCtrl', DashboardCtrl);

function DashboardCtrl(profile,$scope) {
  this.user_profile = profile;
}

HEre is the reference

Update:

You can use the redirection in the resolve like,

resolve: {
  profile: function (UserService,$state) {
    return UserService.getUser().then(function(profile){
    if (profile.id) {
        return profile;
  } else {
        $state.go('/')
  }
  },
}

Upvotes: 1

Related Questions