本文介绍了angularjs 2.0:无法通过组件Constructor()注入任何东西的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用angularjs 2.0创建一个示例应用程序.在开发过程中,我遇到了一个严重的问题-我无法通过构造函数向组件注入任何东西.

I am creating a sample application in angularjs 2.0. While developement I came across with a serious problem - I can't inject anything to the component through the constructor function.

这是plnkr网址: https://plnkr.co/edit/g1UcGmYPLtY8GiXuNHzK?p=预览

This is the plnkr url : https://plnkr.co/edit/g1UcGmYPLtY8GiXuNHzK?p=preview

我使用以下代码从app.item.service.ts导入ItemService

I used the following code for importing ItemService from app.item.service.ts

import { ItemService } from './app.item.service';

然后我将提供者指定为

@Component({
  selector: 'list-todo',
  template: `
    <ul>
    <li *ngFor="let item of items">{{item.text}}</li>
    </ul>
  `,
  providers : [ItemService]
})

之后,给TodoComponent指定代码

After that, given code for TodoComponent as

export class TodoComponent implements OnInit {
  items:Array<Object> = [];
  constructor(private itemService: ItemService){  //here is the problem
   }

  ngOnInit(){
    this.getItems();
  }
  getItems(){
    this.items = this.itemService.getItems();
  }
}

当我尝试通过构造函数注入ItemService时,出现错误:错误:无法解析TodoComponent的所有参数:(?)."我什至无法注入Injector之类的angularjs提供程序.

When I try to inject ItemService through constructor , I am getting an error : " Error: Can't resolve all parameters for TodoComponent: (?)."I am not able to inject even angularjs providers like Injector.

但是,此方法对我有用:

However, this method works for me :

const injector =  ReflectiveInjector.resolveAndCreate([ItemService]);
this.itemService = injector.get(ItemService);

我正在使用package.json中提到的以下版本的库进行开发

I am using the following versions of libraries for developement as mentioned in my package.json

 "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/router": "3.0.0",
    "@angular/upgrade": "2.0.0",
    "core-js": "^2.4.1",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.12",
    "systemjs": "0.19.27",
    "zone.js": "^0.6.23",
    "angular2-in-memory-web-api": "0.0.20",
    "bootstrap": "^3.3.6"
  },
  "devDependencies": {
    "concurrently": "^2.2.0",
    "lite-server": "^2.2.2",
    "typescript": "^2.0.2",
    "typings":"^1.3.2"
  }

  • 角度版本:最终版本2.0.0
  • 浏览器:全部
  • 附加我从控制台获得的错误日志:

    attaching the error log I got from console :

    (index):16 Error: Error: Can't resolve all parameters for TodoComponent: (?).
            at CompileMetadataResolver.getDependenciesMetadata (http://localhost:3000/node_modules/@angular/compiler/bundles/compiler.umd.js:14404:21)
            at CompileMetadataResolver.getTypeMetadata (http://localhost:3000/node_modules/@angular/compiler/bundles/compiler.umd.js:14301:28)
            at CompileMetadataResolver.getDirectiveMetadata (http://localhost:3000/node_modules/@angular/compiler/bundles/compiler.umd.js:14074:30)
            at eval (http://localhost:3000/node_modules/@angular/compiler/bundles/compiler.umd.js:14167:51)
            at Array.forEach (native)
            at CompileMetadataResolver.getNgModuleMetadata (http://localhost:3000/node_modules/@angular/compiler/bundles/compiler.umd.js:14161:51)
            at RuntimeCompiler._compileComponents (http://localhost:3000/node_modules/@angular/compiler/bundles/compiler.umd.js:16803:49)
            at RuntimeCompiler._compileModuleAndComponents (http://localhost:3000/node_modules/@angular/compiler/bundles/compiler.umd.js:16741:39)
            at RuntimeCompiler.compileModuleAsync (http://localhost:3000/node_modules/@angular/compiler/bundles/compiler.umd.js:16732:23)
            at PlatformRef_._bootstrapModuleWithZone (http://localhost:3000/node_modules/@angular/core/bundles/core.umd.js:6954:29)
        Evaluating http://localhost:3000/dist/main.js
        Error loading http://localhost:3000/dist/main.js(anonymous function) @ (index):16ZoneDelegate.invoke @ zone.js:203Zone.run @ zone.js:96(anonymous function) @ zone.js:462ZoneDelegate.invokeTask @ zone.js:236Zone.runTask @ zone.js:136drainMicroTaskQueue @ zone.js:368ZoneTask.invoke @ zone.js:308
    

    推荐答案

    我发现您的tsconfig.json不正确.

    I see that your tsconfig.json isn't correct.

    {
      "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": false,
        "emitDecoratorMetadata": true, <== it should be true
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": false,
        "outDir": "dist"
      }
    }
    

    这是DI的神奇调味料. emitDecoratorMetadata:是.此选项会将类型信息保留在对象的元数据中.

    This is the magic sauce for DI. emitDecoratorMetadata: true. This option will preserve type information in your object's metadata.

    另请参见

    • How does the TypeScript Angular DI magic work?
    • Injecting services in services in Angular 2

    这篇关于angularjs 2.0:无法通过组件Constructor()注入任何东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-25 03:29