Angular 2服务未注入组件 [英] Angular 2 service not being injected into component

查看:86
本文介绍了Angular 2服务未注入组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular2(2.0.0-beta.0)应用程序中定义了一个服务.就像这样:

I have a service defined in my Angular2 (2.0.0-beta.0) application. It's something like this:

import {Injectable} from "angular2/core";

@Injectable()
export class MyService {
    constructor() {

    }

    getSomething() {
        return 'something';
    }
}

我在我的主应用程序文件的bootstrap()函数中列出了它,以便通常可以将其提供给我的代码:

I have it listed in my bootstrap() function in my main app file so that it should be made available to my code in general:

bootstrap(App, [MyService, SomeOtherService, ROUTER_DIRECTIVES[);

有时,即使我在组件constructor()函数中有类似myService:MyService之类的东西,也无法在组件中使用该服务,

Sometimes I can't use the service in a component, even though I have something like myService:MyService in the component constructor() function, like this:

import {MyService} from '../services/my.service';

@Component({
    selector: 'my-component',
    directives: [],
    providers: [],
    pipes: [],
    template: `
    <div><button (click)="doStuff()">Click Me!</button></div>
    `
})
export MyComponent {
    constructor(myService:MyService) {} // note the private keyword

    doStuff() {
        return this.myService.getSomething();
    }
}

在其他地方也可以.在无法正常工作的地方,我会收到一条消息,如尝试访问它:

In other places it works fine. In places where it doesn't work, I get a message like if I try to access it:

EXCEPTION: TypeError: Cannot read property 'getSomething' of undefined

这基本上意味着服务没有被注入.

It basically means the service was not injected.

是什么原因导致它无法注入?

What is causing it to not be injected?

推荐答案

问题是,除非您在构造函数中将注入的对象标记为privatepublic,否则似乎依赖注入不会起作用.

The problem is that it appears that the dependency injection won't work unless you have the injected objects in the constructor marked as either private or public.

在我的组件的构造函数中的服务注入之前添加这两件事中的任何一项,使其工作正常:

Adding either of those two things in front of the service injection in my component's constructor made it work fine:

import {MyService} from '../services/my.service';

@Component({
    selector: 'my-component',
    directives: [],
    providers: [],
    pipes: [],
    template: `
    <div><button (click)="doStuff()">Click Me!</button></div>
    `
})
export MyComponent {
    constructor(private myService:MyService) {} // note the private keyword

    doStuff() {
        return this.myService.getSomething();
    }
}

这篇关于Angular 2服务未注入组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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