Angular 2 Di not working - cannot resolve all parameters for
Asked Answered
A

3

16

I've created a simple Hello World app that works fine. But when I want to add a "Service" just a simple Di I got the following errors:

angular2.dev.js:23877 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.

angular2-polyfills.js:469 Unhandled Promise rejection: 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. ; Zone: angular ; Task: Promise.then ; Value:

I've 3 Files

boot.ts:

///<reference path="../../node_modules/angular2/typings/browser.d.ts"/>
import {bootstrap} from 'angular2/platform/browser'
import {AppComponent} from './mainApp'
bootstrap(AppComponent);

mainApp.ts:

import {Component} from 'angular2/core';
import {CourseService} from './course.service';


@Component({
    selector: 'my-app',
    template: 'My First Angular 2 App',
    providers: [CourseService],
})
export class AppComponent {
    constructor(courseService: CourseService) {
    }
} 

course.service.ts:

export class CourseService {
   public getCourses(): string[] {
      let courses: string[] = ["Course 1", "Course 2", "Course 3"];
      return courses;
  }
}

when I remove then parameters from the constructor every thing works fine.

thats the head of my HTML document and I ma using angular 2 beta 13:

<script src="~/Scripts/es6-shim.min.js"></script>
<script src="~/Scripts/system-polyfills.js"></script>
<script src="~/Scripts/shims_for_IE.js"></script>
<script src="~/Scripts/angular2-polyfills.js"></script>
<script src="~/Scripts/system.js"></script>
<script src="~/Scripts/Rx.js"></script>
<script src="~/Scripts/angular2.dev.js"></script>

<!-- 2. Configure SystemJS -->
<script>
    System.config({
        packages: {
            'ScriptsApp/views': {
                defaultExtension: 'js'
            }
        }
    });
</script>
<script>
    System.import('ScriptsApp/views/boot').then(null, console.error.bind(console));
</script>

Update these are NOW my Fixed csproj TypeScript Settings

<TypeScriptTarget>ES5</TypeScriptTarget>
<TypeScriptJSXEmit>None</TypeScriptJSXEmit>
<TypeScriptCompileOnSaveEnabled>True</TypeScriptCompileOnSaveEnabled>
<TypeScriptNoImplicitAny>False</TypeScriptNoImplicitAny>
<TypeScriptModuleKind>CommonJS</TypeScriptModuleKind>
<TypeScriptRemoveComments>False</TypeScriptRemoveComments>
<TypeScriptOutFile />
<TypeScriptOutDir />
<TypeScriptGeneratesDeclarations>False</TypeScriptGeneratesDeclarations>
<TypeScriptNoEmitOnError>True</TypeScriptNoEmitOnError>
<TypeScriptSourceMap>True</TypeScriptSourceMap>
<TypeScriptMapRoot />
<TypeScriptSourceRoot />
<TypeScriptExperimentalDecorators>True</TypeScriptExperimentalDecorators>
<TypeScriptEmitDecoratorMetadata>True</TypeScriptEmitDecoratorMetadata>

In the Newest VS 2015 Update you can also use the tsconfig.json, then the Solution Settings for TypeScript are ignored. My current example for my tsconfig.json:

 {
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    //Kümmert sich um die Typings das diese entsprechend gefunden werden, keine Reference mehr in boot.js notwendig. Geht aber in VS nicht!
    //"lib": ["es6"],
    "types": [
      "node" //wird für RequireJs benötigt, damit z.b. der Typ gefunden werden kann
    ]
  },
  //Wird für den AwesomeTypeScriptLoad in WebPack benötigt!
   "awesomeTypescriptLoaderOptions": {
     "useWebpackText": true
   },
  "exclude": [
       "node_modules",
       "dist",
       "typings/main",
       "typings/index.d.ts"
     ],
     "compileOnSave": true
   }
Acerbic answered 1/4, 2016 at 18:21 Comment(2)
Your code looks good. Perhaps something wrong with the CourseService import.Hummock
If something should be wrong with the import, TypeScript should bring an error. wenn I remove the "./" in the beginning I get an error, so I've no clue where my Problem is. I am using ASP.NET 4 at the moment but when the simple hello world works why not the DiAcerbic
H
31

Update

After update in question OP is using Typescript already, I'd suggest you to add emitDecoratorMetadata: true inside your tsconfig.json. It is necessary so the JavaScript output creates the metadata for the decorators inside a transpiled script file.


You need to Add @Inject to create an instance of CourseService inside AppComponent

constructor(@Inject(CourseService) courseService: CourseService) {
}

In a case if you are using typescript, you don't need to have @Inject decorator there in place. Typescript done that for you.

Handcraft answered 1/4, 2016 at 20:4 Comment(2)
Worked for me, Angular 4 with TypeScript. Thanks!Valladares
@PankajParkar Hi, I got stuck on Angular 1 testcase.. Pls help stackoverflow.com/q/42671744/3297613.Outrigger
G
9

I was able to solve this problem by adding:

import {Inject} from '@angular/core';

in the component and annotating the service to be injected with:

constructor(@Inject(CourseService) courseService: CourseService) {
Gwen answered 6/8, 2016 at 16:35 Comment(2)
it worked for me after adding import {Injectable} from '@angular/core' to the service class and then decorating it with @Injectable() decorator.Needle
Although this works, it should be done by default, Angular should find the service which has been marked as @Injectable() when defined, also this is happening for core angular servces like Http, I have to do it like: private http: Http; constructor(@Inject(Http) http: Http) { this.http = http; }Leena
C
0

In my case the issue was caused by @angular/forms . If you are using it near the faulty component start checking your @angular/forms and find a fix around it.

Chalcanthite answered 31/5, 2017 at 14:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.