javascriptangularangular2-di

How does @Host decorator work in injector tree


I'm trying to understand how the @Host decorator works uncoupled from view-components. So I created the following injector tree:

class Dependency {
}

@Injectable()
class NeedsDependency {
  constructor(@Host() public dependency: Dependency) {
    console.log(this.dependency); // outputs 'A', but I expected the error
  }
}

const parent = ReflectiveInjector.resolveAndCreate([{provide: Dependency, useValue: 'A'}]);
const child = parent.resolveAndCreateChild([]);
const grandchild = child.resolveAndCreateChild([NeedsDependency]);
grandchild.get(NeedsDependency);

I expected to get an error, because as I understand the host for grandchild injector is child, and there is no Dependency provided in the child injector. However, when I run this code, I get 'A' injected from the root injector. Why?


Solution

  • Host doesn't have semantic meaning in the context of plain ReflectiveInjector.resolveAndCreate injector.

    It is just ignored when being used outside the compiler.

    For the desired behaviour,

    I expected to get an error, because as I understand the host for grandchild injector is child, and there is no Dependency provided in the child injector.

    consider using Self instead.