0

Refer to code:

https://plnkr.co/edit/j5qPROsWX2mGCQMIigee?p=info

It goes something like:

import {Component, Inject, provide} from 'angular2/core';
import {Hamburger} from '../services/hamburger';

@Component({
  selector: 'app',
  template: `Bun Type1: {{ bunType1 }}
  <br/>
  Are these same instances : {{equality}} 
  `
})
export class App {
  bunType: string;
  constructor(@Inject(Hamburger) h1, @Inject(Hamburger) h2) {
    this.bunType1 = h1.bun.type;


    if (h1 === h2) {
      this.equality = 'true'; //this is the outcome
    } else {
      this.equality = 'false';
    }

  }
}

In the app class, we are injecting two different variables h1 and h2. I call them different because I believe the angular2 framework does something like

h1 = new Hamburger()
h2 = new Hamburger()

and now injects two different objects into App constructor. If that is the case then howcome we get the result (h1 === h2) = true?

runtimeZero
  • 26,466
  • 27
  • 73
  • 126

1 Answers1

-1

Because you specified the provider for the Hamburger class when bootstrapping your application, the corresponding instance is a singleton (instantiate once and then this instance is always used) for the whole application.

bootstrap(AppComponent, [ Hamburger, (...) ]);

For that reason, when injecting a parameter with this provider (the Hamburger class), you will always have the same instance (even if you inject twice).

It doesn't depend on the names of parameters (h1 and h2) but on the tokens (in @Inject or the class names) you use.

It's the way dependency injection (and hierarchical injectors) works in Angular2. For more details, you could have a look at this question:

This behavior allows for example to implement shared services, i.e. share à same service instance between several components with dependency injection.

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360