无法注入ComponentFactoryResolver

时间:2018-05-20 08:35:15

标签: javascript angular typescript

我尝试使用ComponentFactoryResolver来创建动态角度组件。下面是我注入ComponentFactoryResolver的代码。

import { Component, ComponentFactoryResolver, OnInit, ViewChild } from "@angular/core";

@Component({
    selector: "app-component",
    template: `
        <h1>{{title}}</h1>
    `
})
export default class AppComponent implements OnInit {

    private title = "Hello World";


    constructor(private componentFactoryResolver: ComponentFactoryResolver){

    }

    ngOnInit() {}


}

它在浏览器控制台中抛出以下异常。

Error: Can't resolve all parameters for AppComponent: (?).

使用的依赖项(package.json)。我使用webpack编译js并在HTML中包含用于运行的js。

{
  "name": "angular_hello_world_example",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "watch": "webpack --progress --colors --watch"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@angular/common": "^5.1.3",
    "@angular/compiler": "^5.1.3",
    "@angular/core": "^5.1.3",
    "@angular/platform-browser": "^5.1.3",
    "@angular/platform-browser-dynamic": "^5.1.3",
    "core-js": "^2.5.3",
    "rxjs": "^5.5.6",
    "zone.js": "^0.8.19"
  },
  "devDependencies": {
    "@types/node": "^9.3.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "ts-loader": "^3.1.1",
    "typescript": "^2.6.1"
  }
}

模块声明的附加信息

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import AppComponent from './AppComponent';


@NgModule({
    declarations: [
      AppComponent
    ],
    imports: [
      BrowserModule
    ],
    providers: [],
    bootstrap: [AppComponent]
  })
export default class AppModule {


}

1 个答案:

答案 0 :(得分:1)

谢谢@estus。这是由于错误的ts配置。 tsconfig.json中缺少emitDecoratorMetadata。

<强> tsconfig.json

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "sourceMap": true,
        "outDir": "target",
        "moduleResolution": "node",
        "allowJs": true,
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true
    },
    "include": [
        "src/**/*"
    ]
}