Josef Sábl
Josef Sábl

Reputation: 7732

Angular2 dependency injection doesn't work as described in official tutorial

I am following this tutorial. And I am stuck. Even if I copy the exact code it doesn't do what it is supposed to. Maybe it is based on some older beta? Or maybe I am overlooking something.

You can see complete sources on the bottom of the page, I will just copy paste the most important parts here.

I need to inject HeroService into AppComponent. But the automatic injection does not happen. See the comment at the last line of code.

The service:

import { Injectable } from 'angular2/core';
import { HEROES } from './mock-heroes';

@Injectable()
export class HeroService {
    getHeroes() {
        return HEROES;
    }
}

The component:

import { Component, OnInit } from 'angular2/core';
import { HeroService } from './hero.service';

@Component({
    selector: 'my-app',
    template: ` .... snip ....`,
    styles: [` .... snip ....`],
    directives: [HeroDetailComponent],
    providers: [HeroService]
})
export class AppComponent implements OnInit {   
    constructor(private heroService: HeroService) {
        alert(heroService); //!!!!! This is undefined
        alert(this.heroService); //!!!!! This is undefined as well
    };
}

The tutorial states that if I omit the providers part I get the error. But that is actually not the case and even if I comment it out it behaves same.

My version of Angular2 is 2.0.0-beta.17

Upvotes: 0

Views: 239

Answers (2)

Josef Sábl
Josef Sábl

Reputation: 7732

The problem is caused by my version of Angular2 which is beta 17. JSPM won't let me install higher version (This autoinjection obviously needs RC 1).

My temporary fix is to change the component to:

import { Component, OnInit, Inject } from 'angular2/core';
import { HeroService } from './hero.service';

@Component({
    selector: 'my-app',
    template: ` .... snip ....`,
    styles: [` .... snip ....`],
    directives: [HeroDetailComponent],
    providers: [HeroService]
})
export class AppComponent implements OnInit {   
    constructor(@Inject(HeroService) private heroService: HeroService) { //<---- the change
        alert(heroService); //[Object object]
    };
}

Upvotes: 0

Thierry Templier
Thierry Templier

Reputation: 202138

Try the following:

export class AppComponent implements OnInit {   
  constructor(private heroService: HeroService) {
    alert(this.heroService); // <------
  }
}

That being said, both should work. It actually works for me with RC1. See this plunkr: https://plnkr.co/edit/lG5DAd6ceLOIiT5WvYHI?p=preview.

Upvotes: 1

Related Questions