0

I have been trying to find a way to implement angular routing which routes based on a condition rather than which link the user clicks

route1 -> view1 route2 -> view2

To add complication, the condition itself is evaluated on the result of a service. I am retrieving a set of items for my shopping cart checkout app. I need the shopping cart to route to view1 if the number of items is > 0. And a different route if it is 0.

if (itemListService.getItems().length > 0) --> route1

else --> route2

And because of this, the complication which arises is that the routing has to wait until the service result is evaluated before loading the corresponding view. In other words, the promise of the service has to be resolved.

I found the following post where someone suggested using 'resolve' configuration property within the routeprovider, but that only solves the issue of waiting for the service response. I'm not sure if it satisfies checking a condition based on the service response.

Redirecting to a certain route based on condition

Can someone help me with this? Would ui-router be able to implement this better than routeProvider?

Community
  • 1
  • 1
Sankar Vikram
  • 81
  • 2
  • 7

1 Answers1

0

Yes,It can be easily done using ui-router.For example,create four states: the dashboard state,which links you to the resolver state.On entering your resolver state based on your service's data you can redirect to appropriate state.This is done with the help of OnEnter hook of the resolver state.

Demo Plunker

In the plunker,

  1. Click on parent in dashboard
  2. It will navigate to state child1 until the items in service has values
  3. When all the items is popped out it will navigate to state child2

Code:

 var myapp = angular.module('myapp', ["ui.router"]);
 myapp.config(function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise("/dashboard")
  $stateProvider
    .state('dashboard', {
      url: '/dashboard',
      templateUrl: 'dashboard.html'
    }).state('parent', {
      url: '/parent',
      resolve: {
        stateToGo: function(service) {
          if (service.getItems().length > 0) {
            return 'child1';
          } else {
            return 'child2';
          }
        }
      },
      onEnter: function(stateToGo, $state) {
        $state.go(stateToGo);
      }
    })
    .state('child1', {
      templateUrl: 'child1.html',
      resolve: {
        service: function(service) {
          return service;
        }
      },
      controller: function($scope, service) {
        console.log(service.getItems());
        service.removeItem();
        console.log(service.getItems());
      }
    }).state('child2', {
      templateUrl: 'child2.html'
    });
});

myapp.factory('service', [function() {
  var items = [1, 2];
  return {
    getItems: function() {
      return items;
    },
    removeItem: function() {
      items.pop();
    }
  };
}]);
Raghu
  • 909
  • 7
  • 23