typescript - Angular 没有 NameService 的提供者

标签 typescript angular systemjs

我在将类加载到 Angular 组件时遇到问题。很长一段时间以来,我一直在努力解决它;我什至尝试将它们全部合并到一个文件中。我拥有的是:

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;
    }
}

我不断收到一条错误消息,提示 No provider for NameService

有人可以帮我找出代码中的问题吗?

最佳答案

你必须使用 providers 而不是 injectables

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

Complete code sample here .

关于typescript - Angular 没有 NameService 的提供者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30580083/

相关文章:

javascript - Angular typescript如何将字符串转换为html对象并将其传递给变量

typescript - ReasonML 与 TypeScript

angular - 单击按钮后将下拉菜单重置为默认值

javascript - 如何使用 SystemJS 指定库依赖项?

javascript - 如何在 Systemjs builder 任务中包含 zone.js、reflect-metadata 等?

typescript - 预计会出现错误,但代码编译正常

typescript - TypeScript 编译器在 Windows 上使用什么 JavaScript 引擎?

angular - Angular 单页应用程序 (SPA) 的 Shibboleth 身份验证

arrays - 在 ngIf 中使用 array.prototype.some

javascript - ES6 通过 jspm 在 Firefox、Edge、Vivaldi 中出错,但在 Chrome、Opera 中工作