javascript - 注入(inject) ComponentFactoryResolver 失败

标签 javascript angular typescript

我尝试使用 ComponentFactoryResolver 来创建动态 Angular 组件。下面是我注入(inject) 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 并将 js 包含在 HTML 中运行。

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


}

最佳答案

谢谢@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/**/*"
    ]
}

关于javascript - 注入(inject) ComponentFactoryResolver 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50433040/

相关文章:

javascript - Angular 异步调用与 react 和 Node 异步调用中的“this”引用

angular - 如何在 ionic html模板中编写条件语句

typescript - 使用 webpack、threejs 示例和 typescript?

javascript - 使用POST方法给用户授权::Angular2&TypeScript

javascript - 避免 CSS 中的重复

JavaScript 与 IE8 的不兼容问题

javascript - jQuery AJAX 文件上传 PHP

javascript - 如何使用 webpack 从 node_modules 目录添加 Font Awesome

Angular 9 变量未在 View 中更新

javascript - 使用类验证器中的 @MinDate 会导致 TypeError : Cannot read property 'getTime' of undefined?