1
votes

I have a basic Angular Dart program which currently allows logging in and shows a basic dashboard when logged in. What I would like to do is redirect to the dashboard route after a successful login. I do not know how to access the router object from within the login controller, attempts to use DI to load in Router to the controller work but give me a fresh Router object instead of the previously initialised one (as expected).

main.dart

import 'package:angular/angular.dart';
import 'dart:convert' show JSON;
import 'dart:html';

class TTRouter implements RouteInitializer {

  Cookies _cookies;

  TTRouter(this._cookies);

  init(Router router, ViewFactory view) {
    router.root
      ..addRoute(
          name: 'login',
          path: '/login',
          enter: view('login.partial.html'))
      ..addRoute(
          name: 'home',
          path: '/dashboard',
          enter: view('dashboard.partial.html'));
  }

}

@NgController(
    selector: '[login-controller]',
    publishAs: 'ctrl')
class LoginController {
  Http _http;
  Scope _scope;

  LoginController(this._scope, this._http);

  login() {
    // Login API request ommitted
    // TODO: insert redirect to 'home' route here
  }
}


class TTModule extends Module {
  TTModule() {
    type(RouteInitializer, implementedBy: TTRouter);
    type(LoginController);

    factory(NgRoutingUsePushState,
        (_) => new NgRoutingUsePushState.value(false));
  }
}

main() => ngBootstrap(module: new TTModule());

login() is called using ng-submit="ctrl.login() from the login partial view.

I would be grateful for any comments on the structure of the code as well if I'm approaching this the wrong way. I am new to both Dart and Angular (read/watched tutorials but this is the first app I am building on my own).

3

3 Answers

3
votes

If you add the router as value to the module instead of type you get the same instance every time.

TTModule() {
  value(RouteInitializer, new TTRouter());
}
1
votes

try with NgRoutingHelper.

class LoginController {
  Http _http;
  Scope _scope;

  NgRoutingHelper locationService;
  LoginController(this._scope, this._http, NgRoutingHelper this.locationService );

  login() {
    // Login API request ommitted
    // TODO: insert redirect to 'home' route here
    locationService.router.go('home', {} );
  }
}

don't forget to add the service in your module

type(NgRoutingHelper );
1
votes

You should be always getting the same instance of the Router -- there can only be one, otherwise unpredictable things will start happening.

class LoginController {
  Http _http;
  Scope _scope;
  Router _router;

  LoginController(this._scope, this._http, this._router);

  login() {
    _router.go('home', {} );
  }
}