1

I have the following angular2 app with a simple dependency injected and it doesn't work. What am I missing?

Here's the error:

EXCEPTION: Cannot resolve all parameters for 'AppComponent'(?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'AppComponent' is decorated with Injectable.

and the code:

import {Component} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';

class DataService {
    items: Array<any>;

    constructor() {
        this.items = [
            { name: 'Christoph Burgdorf' },
            { name: 'Pascal Precht' },
            { name: 'thoughtram' }
        ];
    }

    getItems() {
        return this.items;
    }
}


@Component({
    selector: 'app',
    providers: [DataService],
    template: `
    <ul>
      <li *ngFor="#item of items">{{item.name}}</li>
    </ul>
  `
})
class AppComponent {
    items: Array<any>;
    constructor(dataService: DataService) {
        this.items = dataService.getItems();
    }
}

bootstrap(AppComponent, []);
3
  • You have DataService and AppComponent in the same file and in the same order inside the file? Commented Mar 8, 2016 at 17:22
  • And in the same order? Commented Mar 8, 2016 at 17:23
  • same order too. btw im using angualr2 version:2.0.0-beta.8 Commented Mar 8, 2016 at 17:25

1 Answer 1

1

Can't reproduce. I added your code to a Plunker

https://plnkr.co/edit/0DTjG5?p=preview

and it seems to work fine with or without @Injectable().

It is suggested to always add @Injectable() to services but it is only required when the service has constructor parameters.

.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the plnkr. I think there was something wrong with my project setup. I basically copied your <script scr"... tags to import things in the the order of the plnkr and also copied your config.js file. That solved the problem. Not sure what the root cause was though, but it's fixed. Thanks!
I have seen that mentioned a few times already. No idea what causes it though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.