Angular 2服务未注入组件

Mic*_*ryl 4 typescript angular2-services angular2-injection angular

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

import {Injectable} from "angular2/core";

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

    }

    getSomething() {
        return 'something';
    }
}
Run Code Online (Sandbox Code Playgroud)

我把它放在我的主应用程序文件中的bootstrap()函数中,以便它通常可用于我的代码:

bootstrap(App, [MyService, SomeOtherService, ROUTER_DIRECTIVES[);
Run Code Online (Sandbox Code Playgroud)

有时我不能在组件中使用该服务,即使我myService:MyService在组件constructor()函数中有类似的东西,如下所示:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

在其他地方它工作正常.在它不起作用的地方,我收到一条消息,如果我尝试访问它:

EXCEPTION: TypeError: Cannot read property 'getSomething' of undefined
Run Code Online (Sandbox Code Playgroud)

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

是什么导致它不被注射?

Rom*_*ain 12

这种行为完全正常.

在组件的构造函数方法中,当您不添加privatepublic关键字时,myService变量被计算为局部变量,因此它在方法调用结束时被销毁.

当您添加privatepublic关键字时,TypeScript会将该变量添加到class属性中,以便稍后使用关键字调用该属性.

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.
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*ryl 9

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

在我的组件的构造函数中在服务注入之前添加这两个东西中的任何一个使它工作正常:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我和我的完全一样,我仍然得到'myservice'在运行时没有定义错误 (3认同)