Shailen Tuli
Shailen Tuli

Reputation: 14171

Accessing route parameters in Angular Dart

I have a dead-simple routing case that does not involve mapping views to routes. Instead, I want to parse the route/uri and set the value of some variable in my controller. So, for instance, if the route is #/foo I want to set one value, and if it is #/bar I want to set another value.

I don't have a simple pattern for doing this. Currently, I am doing something like this in my controller:

TodoController(this.http, this.scope, this.router) {
  router.onRouteStart.listen((RouteStartEvent event) {
    event.completed.then((result) {
      if (result) {
        if (event.uri == '/foo') {
          myVar = ...
        } else if (event.uri == '/bar') {
          myVar = ...
        } else {
          // ...
        }
      }
    });
  });
}

This strikes me as a clunky approach, but I'm not coming up with anything much better. Anyone have a better idea how I can monitor the route changes in my controller?

Upvotes: 3

Views: 443

Answers (1)

pavelgj
pavelgj

Reputation: 2701

You can do something like this:

bool isFoo = false;
bool isBar = false;
router.root
    ..addRoute(
        name: 'foo',
        path: '/foo',
        enter: (_) => isFoo = true,
        leave: (_) => isFoo = false)
    ..addRoute(
        name: 'bar',
        path: '/bar',
        enter: (_) => isBar = true,
        leave: (_) => isBar = false);

If you want to listen to route changes at a later stage, for example inside a component/controller, then you do it like this:

class MyController implements NgDetachAware {
  bool isFoo = false;
  bool isBar = false;

  RouteHandle fooHandle;
  RouteHandle barHandle;

  MyController(Router router) {
    fooHandle = router.root.getRouter('foo').newHandle();
    fooHandle.onEnter.listen((_) => isFoo = true);
    fooHandle.onLeave.listen((_) => isFoo = false);
    barHandle = router.root.getRouter('bar').newHandle();
    barHandle.onEnter.listen((_) => isBar = true);
    barHandle.onLeave.listen((_) => isBar = false);
  }

  detach() {
    fooHandle.discard();
    barHandle.discard();
  }
}

Note that in this example I'm using RouteHandle that helps us cleanup all listeners when controller is destroyed.

Upvotes: 2

Related Questions