Can I inject a service into CanActivate?

Issue

Unlike the other hooks, CanActivate is a function separated from the component.

import 'dart:async';
import 'package:angular2/core.dart';
import 'package:angular2/router.dart';

@Component(selector: 'my-app', template: '<h1>Hello World!</h1>')
@CanActivate(someGuard)
class HelloComponent {}

FutureOr<bool> someGuard(ComponentInstruction next, ComponentInstruction prev) {
  return true;
}

AFAIK, it is possible to intercept the root injector at bootstrap time and assign it to a global variable, so that I can access it anywhere. IMO, that sounds like a hack and I don’t like it. Is there a proper way to inject a service in CanActivate hook?

Solution

Angulars DI only supports constructor injection. @CanActivate() is an annotation and therefore doesn’t support DI.

There is a workaround though.

Create a variable in a library and import it

Injector injector;

assign the injector when the application is created

bootstrap(App, [
  Auth,
  HTTP_PROVIDERS,
  ROUTER_PROVIDERS,
  provide(LocationStrategy, useClass: HashLocationStrategy)
]).then((appRef: ComponentRef) => {
  // store a reference to the application injector
  injector = appRef.injector;
});

then you can import the library with the injector and access it from code someGuard()

Answered By – Günter Zöchbauer

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.