【问题标题】:Angular 2 service not being injected into componentAngular 2服务未注入组件
【发布时间】:2016-03-25 15:18:45
【问题描述】:

我在 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[);

有时我无法在组件中使用该服务,即使我在组件constructor() 函数中有类似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

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

什么原因导致无法注入?

【问题讨论】:

    标签: typescript angular angular2-injection angular2-services


    【解决方案1】:

    这种行为是完全正常的。

    在组件的构造方法中不添加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.
    }
    

    【讨论】:

    • Typescript docs: "关键字publicprivate 还通过创建参数属性为您提供了创建和初始化类成员的简写。这些属性让您可以创建和初始化成员一步到位。”
    【解决方案2】:

    问题在于,除非您在构造函数中将注入的对象标记为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,但我喜欢这种方法..
    • 我的和你的一模一样,但在运行时我仍然得到 'myservice' is not defined 错误
    • 我已经完成了你所说的,但仍然无法正常工作并给出同样的错误
    • 检查这个值,对我来说这是它来自哪里的值
    猜你喜欢
    • 2017-08-14
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多