Angular 2 Di not working - cannot resolve all parameters for

眉间皱痕 提交于 2019-11-30 22:07:11

问题


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
   }

回答1:


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.




回答2:


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) {



回答3:


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.



来源:https://stackoverflow.com/questions/36363279/angular-2-di-not-working-cannot-resolve-all-parameters-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!