Angular 2服务未被注入到组件中

4

我有一个在我的Angular2(2.0.0-beta.0)应用程序中定义的服务。它类似于以下内容:

import {Injectable} from "angular2/core";

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

    }

    getSomething() {
        return 'something';
    }
}

我已将它列在我的主应用程序文件中的bootstrap()函数中,以便它可以在我的代码中通用地使用:
bootstrap(App, [MyService, SomeOtherService, ROUTER_DIRECTIVES[);

有时候我无法在组件中使用服务,即使在组件的构造函数中有类似于myService:MyService这样的东西。如下所示:
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();
    }
}

在其他地方它能够正常工作。但在一些地方,如果我尝试访问它,就会收到类似以下的错误信息:

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

基本上意味着该服务未被注入。
是什么导致它未被注入?
2个回答

12

这种行为是完全正常的。

在组件的构造函数中,如果您没有添加privatepublic关键字,那么myService变量将被视为局部变量,因此在方法调用结束时它会被销毁。

当您添加privatepublic关键字时,TypeScript会将变量添加到类属性中,因此您可以稍后使用this关键字调用该属性。

constructor(myService: MyService) {
  alert(myService.getSomething());
  // This will works because 'myService', is declared as an argument
  // of the 'constructor' method.
}

doStuff() {
  return (this.myService.getSomething());
  // This will not works because 'myService' variable is a local variable
  // of the 'constructor' method, so it's not defined here.
}

1
“public”和“private”关键字还为您提供了一种快捷方式来创建和初始化类成员,即通过创建参数属性。这些属性允许您在一步中创建和初始化成员。”——《Typescript文档》(http://www.typescriptlang.org/Handbook#classes-privatepublic-modifiers) - Mark Rajcok

10
问题在于,似乎只有将构造函数中注入的对象标记为privatepublic,依赖注入才能正常工作。

在我的组件构造函数中添加其中任何一个修饰符,就可以正常工作:

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

我之前一直在构造函数之前声明它们并使用 this.MyService = MyService,但我喜欢这种方法。 - Dennis Smolek
3
我和你的情况一模一样,但我仍然在运行时遇到了“myservice未定义”的错误。 - Ryan Langton
1
我已经按照你说的做了,但仍然无法正常工作并且出现相同的错误。 - Abdeali Chandanwala
检查this值,对我来说它是它来自哪里的值。 - Ben Taliadoros

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接