Angular 2 service not being injected into component

风格不统一 提交于 2019-12-04 11:09:09
Romain

This behaviour is totally normal.

In the constructor method of the component when you don't add the private or public keyword the myService variable is evaluated as a local variable, so it's destroyed at the end of the method call.

When you add private or public keyword, TypeScript will add the variable to the class property, so you can later call the property with this keyword.

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

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();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!