Understanding dependency injection in angular2

Here is a snippet of code

@Component({
     ... : ...
     providers: [MyService]
})
export class MyComponent{

     constructor(private _myService : MyService){
     }

     someFunction(){
          this._myService.getSomething();
     }
}

And here is my understanding / question of how this works in angular2 / typescript.

  • A singleton object will be created whenever we write MyServiceto providers.
  • Why give it in the constructor? Can we do it somewhere else?
  • whoever calls the constructor (possibly a javascript engine), how does he know what to pass to the arguments
  • or am I mistaken, is that not even an argument?

EDIT

  • what if i provide providers: [MyService]on two controllers. Will he create a new instance or a choice from one?
+4
source share
1 answer
  • provider: [ ... ] , . - , providers: [ ... ] ( ). bootstrap(AppComponent, [SomeProvider]) , , .

  • Angular2 -. , .

  • Angular contructor, , , .
    @Injectable(), , .

  • DI ( ) . () . , , .
    , DI.

""

bootstrap(...), providers: [...], .

( ), DI bootstrap() . ( bootstrap(...)

: , .

+2

All Articles