我正在尝试创建一个角度(beta7)应用程序。在顶部应该有一个MenuComponent
使用NavigationService
导航到我的应用程序的不同部分。我希望它NavigationService
是单例的,因此我用bootstrap(...)
. 我知道您也可以在其中添加提供程序,@Component()
但据我所知,这意味着这些提供程序不是单例的,而是每个实例创建的。
但是我收到以下异常:
NavigationService 没有提供者!(菜单组件 -> 导航服务)
这是我的代码:
引导.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();
应用程序.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 {
}
应用程序.html
<hc-menu>Loading menu...</hc-menu>
<div class="container-fluid">
<router-outlet></router-outlet>
</div>
菜单.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);
}
}
导航服务.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 }]);
}
}