Restricting provider lookup

Just like we can restrict dependency injection, we can constrain dependency lookup to the immediate upper level only. To do so, we just need to apply the @Host() decorator to those dependency parameters whose provider lookup we want to restrict:

import {Component, Host} from '@angular/core';

@Component {
selector: 'music-player'
}
export class MusicPlayerComponent {
constructor(@Host() playlist:Playlist) {}
}

According to the preceding example, the MusicPlayerComponent injector will look up a Playlist type at its parent component's providers collection (MusicLibraryComponent, in our example) and will stop there, throwing an exception because Playlist has not been returned by the parent's injector (unless we also decorate it with the @Optional() parameter decorator).

To clarify this functionality, let's do another example:

@Component({
selector: 'granddad',
template: 'granddad <father>'
providers: [Service]
})
export class GranddadComponent {
constructor(srv:Service){}
}

@Component({
selector: 'father',
template: 'father <child>'
})
export class FatherComponent {
constructor(srv:Service) {} // this is fine, as GranddadComponent provides Service
}

@Component({
selector: 'child',
template: 'child'
})
export class ChildComponent {
constructor(@Host() srv:Service) {} // will cause an error
}

In this case, we would get an error as the Child component only looks one level up, to try and find the service. As it is two levels up, it does not find it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset