typescriptangularangular2-injectionangular2-services

Angular 2 service not being injected into component


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';
    }
}

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

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?


Solution

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