Class is not injectable if it is defined right after a component with meta annotation

前端 未结 1 1321
谎友^
谎友^ 2021-01-19 10:07

I just started off with Angular2 quick start project. Have a simple application working. I added DataService class, so that the code will have separation of con

相关标签:
1条回答
  • 2021-01-19 11:07

    JavaScript doesn't hoist classes. Either use forwardRef, move DataService to it's own file or move DataService class above MyAppComponent

    @Component({
        'selector': 'my-app',
        template: `<div *ngFor="#item of items">{{item}}</div>`,
        directives: [NgFor],
        providers: [forwardRef(() => DataService)] //taking service as injectable
    })
    export class MyAppComponent {
        items: Array<number>;
        constructor(@Inject(forwardRef(() => DataService)) service: DataService) {
            this.items = service.getItems(); //retrieving list to bind on the UI.
        }
    }
    

    See also
    - Angular 2 error:
    - http://blog.thoughtram.io/angular/2015/09/03/forward-references-in-angular-2.html

    0 讨论(0)
提交回复
热议问题