Angular no provider for NameService

M.Svrcek picture M.Svrcek · Jun 1, 2015 · Viewed 346.8k times · Source

I've got a problem loading a class into an Angular component. I've been trying to solve it for a long time; I've even tried joining it all in a 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;
    }
}

I keep getting an error message saying No provider for NameService.

Can someone help me spot the issue with my code?

Answer

Klas Mellbourn picture Klas Mellbourn · Aug 30, 2015

You have to use providers instead of injectables

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

Complete code sample here.