Angular 2 service that is not injected into a component

I have a service defined in my Angular2 application (2.0.0-beta.0). This is something like this:

import {Injectable} from "angular2/core";

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

    }

    getSomething() {
        return 'something';
    }
}

I listed it in my bootstrap () function in my main application file so that it is available to my code as a whole:

bootstrap(App, [MyService, SomeOtherService, ROUTER_DIRECTIVES[);

Sometimes I cannot use the service in the component, although I have something like myService:MyServicein a function constructor(), for example:

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 great. In places where this does not work, I get a message, for example, if I try to access it:

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

This basically means that the service has not been introduced.

What makes it not to enter?

+4
source share
2 answers

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

.

, private public, myService , .

private public, 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 not defined here.
}
+11

Source: https://habr.com/ru/post/1620817/


All Articles