This question is specific to Angular 2.
I need to call one of my services, insatiate some objects, and pass them to child controls via injection (I don't want to use a binding for this purpose). How do I do that? In the code below (which does not work) I call blogService to get a CurrentSite object. I need to pass CurrentSite to the NavBar component which is included in the directives attribute of AppComponent.
@Component({
selector: 'my-app',
templateUrl: './app/app.html',
directives: [NavBar, ROUTER_DIRECTIVES],
providers: [HTTP_PROVIDERS, ROUTER_PROVIDERS, BlogService, provide(CurrentSite, { useExisting: this.CurrentSite })]
})
@Routes([
{ path: '/', component: Home },
{ path: '/Contact', component: Contact },
{ path: '/Blog', component: BlogIndex }
])
export class AppComponent implements OnInit {
public CurrentSite: CurrentSite;
constructor(private blogService: BlogService) {
}
ngOnInit()
{
this.SetCurrentSite();
}
SetCurrentSite()
{
this.blogService.GetActiveSites().subscribe(data => {
let site = data.find(x => x.SiteName === "SamsBlog");
if (site === null)
throw new Error("Site SamsBlog was not found");
this.CurrentSite = new CurrentSite();
this.CurrentSite.ID = site.ID;
this.CurrentSite.SiteName = site.SiteName;
});
}
}