【发布时间】:2017-09-12 12:30:31
【问题描述】:
我一直在尝试解决 Angular 2 的一个奇怪问题,它没有检测到我的提供程序声明,但没有任何效果。我什至无法在 plunkr 中复制它。
我在路由器 3.0 alpha.8 中使用 angular 2 rc 3。
错误信息是:ORIGINAL EXCEPTION: No provider for TestService!
app.routes.ts:
import { provideRouter, RouterConfig } from '@angular/router';
import { HomeComponent } from './app/home/home.component';
import { LogInComponent } from './app/log-in/log-in.component';
import { SignUpComponent } from './app/sign-up/sign-up.component';
export const routes: RouterConfig = [
{ path: '', component: HomeComponent },
{ path: 'log-in', component: LogInComponent },
{ path: 'sign-up', component: SignUpComponent }
];
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes)
];
main.ts:
import { bootstrap } from '@angular/platform-browser-dynamic';
import { enableProdMode } from "@angular/core";
import { AppComponent } from './app/app.component';
import { APP_ROUTER_PROVIDERS } from './app.routes';
// enableProdMode();
bootstrap(AppComponent, [
APP_ROUTER_PROVIDERS
])
.catch(error => console.log(error));
app/app.component.ts:
import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
import { TestService } from './shared/test.service';
@Component({
selector: 'my-app',
template: `
<div id="menu">
<a [routerLink]="['/sign-up']"><button>Sign Up</button></a>
</div>
<router-outlet></router-outlet>
`,
directives: [ROUTER_DIRECTIVES],
providers: [TestService]
})
export class AppComponent {
constructor() { }
}
app/sign-up/sign-up.component.ts:
import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
import { TestService } from '../shared/test.service';
@Component({
selector: 'sign-up',
template: `<h1>Sign up!</h1>`,
directives: [ROUTER_DIRECTIVES]
})
export class SignUpComponent {
constructor(private testService: TestService) {
this.testService.test('works?');
}
}
app/shared/test.service.ts:
import { Injectable } from '@angular/core';
@Injectable()
export class TestService {
constructor() { }
test(message: string) {
console.log(message);
}
}
所以,我在基础组件 (app.component.ts) 中提供测试服务,因为我希望我的所有组件都访问同一个实例。但是,当我导航到注册时,我得到了 no provider for testservice 错误。如果我在注册组件中提供 TestService,则可以:
import { Component, OnInit } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
import { TestService } from '../shared/test.service';
@Component({
selector: 'sign-up',
template: `<h1>Sign up!</h1>`,
directives: [ROUTER_DIRECTIVES],
providers: [TestService]
})
export class SignUpComponent implements OnInit {
constructor(private testService: TestService) { }
ngOnInit() { }
}
但是,我需要在整个应用程序中都可以访问同一个实例,那么如何在主组件级别注入它?
我什至尝试使用相同版本的所有内容复制 plunkr 提供的这个应用级服务,但它似乎没有给我同样的错误......
【问题讨论】:
-
它必须与您的项目配置相关。代码很好,这就是它在 Plunker 中运行的原因。
-
您认为哪些配置可能值得怀疑?如果有帮助,我可以发布我的 systemjs 配置
-
我对systemjs了解不多,因为我只是在本地使用Dart。我会尝试使用 angular-cli 创建一个新项目并在那里复制代码位,看看你是否得到同样的错误。
-
您可以发布自己问题的答案。然后您可以接受它(经过 2 天的冷却阶段),这会导致此问题被标记为已回答。
标签: dependency-injection angular