我一直试图解决角度2的一个奇怪的问题,它没有检测到我的提供者声明,但没有任何工作.我甚至无法在plunkr中复制它. 我正在使用角度2 rc 3与路由器3.0 alpha.8. 错误消息是:ORIGINAL EXCEPTIO
我正在使用角度2 rc 3与路由器3.0 alpha.8.
错误消息是:ORIGINAL EXCEPTION:没有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.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() { } }
应用程序/签了/签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?'); } }
应用程序/共享/ test.service.ts:
import { Injectable } from '@angular/core'; @Injectable() export class TestService { constructor() { } test(message: string) { console.log(message); } }
所以,我在基本组件(app.component.ts)中提供了测试服务,因为我希望我的所有组件都能访问同一个实例.但是,当我导航到注册时,我得到了没有提供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与相同版本的一切,但它似乎没有给我同样的错误…
http://plnkr.co/edit/5bpeHs72NrlyUITCAJim?p=preview
在应用程序级别注入一些东西是在bootstrap中完成的:main.ts:
import { TestService } from '../shared/test.service'; bootstrap(AppComponent, [ APP_ROUTER_PROVIDERS, TestService ])