gpt4 book ai didi

routes - Angular2 在可注入(inject)服务中使用路由器

转载 作者:行者123 更新时间:2023-12-02 21:02:56 26 4
gpt4 key购买 nike

我想在服务中使用 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 构造函数中添加 _router: Router 并且它可以在那里工作。如何在我的 ExternalService 中使用 Router 实例?

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

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})])

最佳答案

将路由器直接注入(inject)到服务中似乎工作正常。我还尝试注入(inject)根组件并传递给服务,但是当直接方式工作时,应该不需要

import {Component, Injectable, provide} from '@angular/core';
import {Router, Routes, ROUTER_PROVIDERS, ROUTER_DIRECTIVES} from '@angular/router';
import {LocationStrategy, HashLocationStrategy} from '@angular/common';

@Injectable()
export class ExternalService {
//router:Router;
constructor (private router: Router) {}

navigate() {
this.router.navigate(['/article']);
}
}


@Component({
selector: 'root',
template: `
<h2>Root</h2>
`,
})
export class RootComponent {
}


@Component({
selector: 'article',
template: `
<h2>Article</h2>
`,
})
export class ArticleComponent {
}


@Component({
selector: 'my-app',
providers: [ExternalService, ROUTER_PROVIDERS, provide(LocationStrategy, {useClass: HashLocationStrategy})],
directives: [ROUTER_DIRECTIVES],
template: `
<div>
<h2>Hello {{name}}</h2>
<router-outlet></router-outlet>
</div>
<button (click)="externalService.navigate()">Article</button>
`,
})
@Routes([
{ path: '/article', component: ArticleComponent },
{ path: '/', component: RootComponent }
])
export class App {
constructor(private externalService: ExternalService) {
//externalService.router = router;
this.name = 'Angular2 (Release Candidate!)'
}
}

Plunker example

关于routes - Angular2 在可注入(inject)服务中使用路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37408381/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com