I am trying to fix a strange problem with angular 2 where it does not detect my provider declaration but nothing works. I can’t even play it in plunkr.
I am using angular 2 rc 3 with 3.0 alpha.8 router.
Error message: 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';
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() { }
}
Applications / Registration / 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?');
}
}
application / Shared / test.service.ts:
import { Injectable } from '@angular/core';
@Injectable()
export class TestService {
constructor() { }
test(message: string) {
console.log(message);
}
}
So, I provide the testing service in the base component (app.component.ts) because I want all my components to access the same instance. However, when I go to registration, I do not get a provider for the serviceervice error. If I provide a TestService in the registration component, this works:
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