Routing Angular2在可注入服务中使用路由器

Routing Angular2在可注入服务中使用路由器,routing,angular,Routing,Angular,我想在服务中使用Router对象来允许导航到我的不同路由 我的AppComponent如下所示: @Component({ selector: "app", templateUrl: "app/app.html", directives: [ROUTER_DIRECTIVES] }) @RouteConfig([ { path: "/home", name: "Homepage", component: HomepageComponent,

我想在服务中使用Router对象来允许导航到我的不同路由

我的AppComponent如下所示:

@Component({
    selector: "app",
    templateUrl: "app/app.html",
    directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
  {
    path: "/home",
    name: "Homepage",
    component: HomepageComponent,
    useAsDefault: true
  },{
    path: "/home2",
    name: "Homepage2",
    component: HomepageComponent2
  }
])
export class AppComponent {
    constructor (private _externalService: ExternalService) {}

}
和外部服务:

@Injectable()
export class ExternalService {
    constructor (_router: Router) {}
    ...
}
这段代码说我不能在ExternalService内实例化路由器,但失败了。我想这是因为那里没有RouteConfig。我还尝试在我的
AppComponent
构造函数中添加
\u router:router
,它在那里工作。如何在我的
ExternalService
中使用路由器实例

编辑:这是我的应用程序的引导文件:

import { bootstrap } from "angular2/platform/browser"
import { ROUTER_PROVIDERS } from "angular2/router"
import { ExternalService} from "./utils/external.service"
import { AppComponent } from "./app.component"
import { HTTP_PROVIDERS } from "angular2/http"

bootstrap(AppComponent, [ROUTER_PROVIDERS, HTTP_PROVIDERS, ExternalService, provide(LocationStrategy, {useClass: HashLocationStrategy})])

当您在
bootstrap()
中提供
ExternalService
时,您还必须在那里提供
路由器\u提供程序。否则Angular不知道如何为您的
外部服务实例化
路由器。

bootstrap(AppComponent, [
    ROUTER_PROVIDERS,
    ExternalService
]);
例如用法(似乎很好用)


将路由器直接注入到服务中似乎效果不错。我还尝试注入到根组件并传递到服务,但当直接方式起作用时,就不需要了

从'@angular/core'导入{组件,可注入,提供};
从“@angular/Router”导入{路由器、路由、路由器\提供程序、路由器\指令};
从“@angular/common”导入{LocationStrategy,HashLocationStrategy};
@可注射()
导出类外部服务{
//路由器:路由器;
构造函数(专用路由器:路由器){}
导航(){
this.router.navigate(['/article']);
}
}
@组成部分({
选择器:'根',
模板:`
根
`,
})
导出类根组件{
}
@组成部分({
选择器:'文章',
模板:`
文章
`,
})
导出类组件{
}
@组成部分({
选择器:“我的应用程序”,
提供者:[外部服务,路由器提供者,提供(LocationStrategy,{useClass:HashLocationStrategy}],
指令:[路由器指令],
模板:`
你好{{name}
文章
`,
})
@路线([
{路径:'/article',组件:ArticleComponent},
{path:'/',component:RootComponent}
])
导出类应用程序{
构造函数(私有外部服务:外部服务){
//externalService.router=路由器;
this.name='Angular2(发布候选!)'
}
}