I am in the process of developing an angular (beta7) application. I aim to have a MenuComponent
at the top that utilizes the NavigationService
to navigate throughout different sections of my app. To ensure that the NavigationService
remains a singleton, I am initializing it using bootstrap(...)
. While I am aware that providers can also be added within the @Component()
, my understanding is that this would result in those providers not being singleton but instead created for each instance.
Unfortunately, I encountered the following error:
No provider for NavigationService! (MenuComponent -> NavigationService)
Below is the code snippet:
boot.ts
import {bootstrap} from 'angular2/platform/browser'
import {provide} from 'angular2/core'
import {ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy} from 'angular2/router'
import {HubService} from './services/HubService';
import {ConfigService} from './services/ConfigService';
import {App} from './app';
import {NavigationService} from './services/NavigationService';
var bootstrap_application = function () {
var providers = [
ROUTER_PROVIDERS,
NavigationService,
HubService,
ConfigService,
provide(LocationStrategy, { useClass: HashLocationStrategy })];
bootstrap(App, providers);
};
bootstrap_application();
app.ts
import {Component} from 'angular2/core';
import {ROUTER_DIRECTIVES, RouteConfig} from 'angular2/router'
import {MenuComponent} from './components/menu/menu';
import {HomeComponent} from './components/home/home';
import {RoomComponent} from './components/room/room';
@Component({
selector: 'hc',
templateUrl: 'app/app.html',
directives: [ROUTER_DIRECTIVES, MenuComponent]
})
@RouteConfig([
{ path: "/", name: "Home", component: HomeComponent, useAsDefault: true },
{ path: "/room/:name", name: "Room", component: RoomComponent }
])
export class App {
}
app.html
<hc-menu>Loading menu...</hc-menu>
<div class="container-fluid">
<router-outlet></router-outlet>
</div>
menu.ts
import {Component} from 'angular2/core';
import {Room, ConfigService} from '../../Services/ConfigService';
import {NavigationService} from '../../Services/NavigationService';
@Component({
selector: 'hc-menu',
templateUrl: 'app/components/menu/menu.html'
})
export class MenuComponent {
Rooms: Room[];
IsOpen: boolean;
constructor(private navigationService: NavigationService, private configService: ConfigService) {
this.Rooms = configService.GetRooms();
this.IsOpen = false;
}
toggleOpen() {
this.IsOpen = !this.IsOpen;
}
navigateTo(room: Room) {
this.navigationService.navigateToRoom(room);
}
}
NavigationService.ts
import {Injectable} from 'angular2/core';
import {Router} from 'angular2/router';
import {Room} from './ConfigService'
@Injectable()
export class NavigationService {
router: Router;
constructor(router: Router) {
this.router = router;
}
navigateToRoom(room: Room) {
this.router.navigate(['Room', { name: room.Name }]);
}
}