Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Di not working - cannot resolve all parameters for

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
   }
like image 636
squadwuschel Avatar asked Apr 01 '16 18:04

squadwuschel


People also ask

Which decorator can be used to prevent angular application from breaking if dependency is not resolved?

The Inject decorator is a constructor parameter used to specify a custom provider of a dependency.

Can't resolve all parameters for application module?

You have a dependency in your app module that you did not provide or import in any way. You can determine which by looking at your ApplicationModule constructor method - it likely has some service or similar injected, and you didn't provide it there in imports array of NgModule metadata. Save this answer.

What is inject in angular?

Dependency injection, or DI, is one of the fundamental concepts in Angular. DI is wired into the Angular framework and allows classes with Angular decorators, such as Components, Directives, Pipes, and Injectables, to configure dependencies that they need.


2 Answers

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.

like image 104
Pankaj Parkar Avatar answered Oct 04 '22 21:10

Pankaj Parkar


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) {
like image 34
Stefan D Avatar answered Oct 04 '22 22:10

Stefan D