Angular没有NameService的提供者 [英] Angular no provider for NameService

查看:71
本文介绍了Angular没有NameService的提供者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将类加载到Angular组件时遇到问题.我已经尝试解决很长时间了;我什至尝试将其全部合并到一个文件中.我所拥有的是:

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

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

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

有人可以帮助我发现我的代码中的问题吗?

Can someone help me spot the issue with my code?

推荐答案

您必须使用providers而不是injectables

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

在此处完成代码示例.

这篇关于Angular没有NameService的提供者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆