M.Svrcek M.Svrcek - 3 months ago 14
TypeScript Question

Angular2 no provider for NameService

I've got problem with loading class into Angular2 component. I'm trying to solve for long time, even tried to add it to single file. What i have is:

Application.ts

/// <reference path="../typings/angular2/angular2.d.ts" />

import {Component,View,bootstrap,NgFor} from "angular2/angular2";
import {NameService} from "./services/NameService";

@Component({
selector:'my-app',
injectables: [NameService]
})
@View({
template:'<h1>Hi {{name}}</h1>' +
'<p>Friends</p>' +
'<ul>' +
' <li *ng-for="#name of names">{{name}}</li>' +
'</ul>',
directives:[NgFor]
})

class MyAppComponent
{
name:string;
names:Array<string>;

constructor(nameService:NameService)
{
this.name = 'Michal';
this.names = nameService.getNames();
}
}
bootstrap(MyAppComponent);


services/NameService.ts

export class NameService {
names: Array<string>;
constructor() {
this.names = ["Alice", "Aarav", "Martín", "Shannon", "Ariana", "Kai"];
}
getNames()
{
return this.names;
}
}


All the time I'm getting error message saying "No provider for NameService" ...can someone help me spot that small issue with my code?

Answer

In Angular2 alpha 35 you have to use bindings instead of injectables

@Component({
    selector: 'my-app',
    bindings: [NameService]
})

Complete code sample here.


As of alpha 42, use providers:

@Component({
    selector: 'my-app',
    providers: [NameService]
})