Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 OpaqueToken

Tags:

angular

Need some help with providing an OpaqueToken. Using Angular 2 beta-12. It works fine if provider key is a string, but doesn't work when using OpaqueToken. In Child class, SF is undefined.

Parent Class:

export let SF = new OpaqueToken('sf');

export class A {
  testMsg: string = 'hello';
}

@Component({
  template: `<child></child>`,
  providers: [
    provide(SF, {useValue: A}),
    provide('justString', {useValue: 'hi'}) 
  ]
})
export class App {}

Child class:

import {Component, Injector, Inject, OpaqueToken} from 'angular2/core'
import {SF, A} from './app'
console.log("******", SF); // undefined
@Component({
  selector: 'child',
  template: `
    $$CHILD Rendered$$ {{a}}
  `
})
export class Child {
  //constructor(@Inject(SF) private a: A) {} // doesn't work
  constructor(@Inject('justString') private a: string) {}
}

Exceptions I get:

angular2.min.js:17EXCEPTION: Cannot resolve all parameters for 'Child'(@Inject(undefined)). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'Child' is decorated with Injectable.

like image 625
Elijah Avatar asked Apr 05 '16 20:04

Elijah


1 Answers

It's because you have a cyclic dependency between modules that contain parent and child classes.

If you define your opaque token into a third module and include it in the other ones, it will work.

For example a constant module:

export let SF = new OpaqueToken('sf');

And in the two other modules:

import { SF } from './constants';
like image 175
Thierry Templier Avatar answered Sep 30 '22 20:09

Thierry Templier