【问题标题】:Angular error: Can't resolve all parameters for Component角度错误:无法解析组件的所有参数
【发布时间】:2018-05-08 19:56:00
【问题描述】:

我正在为 Udemy 课程做一个 Angular 练习,但遇到了一个我无法解决的问题。我正在尝试创建一个具有唯一 ID 的 ClickComponent 对象,因此每个对象都有下一次迭代(即 1、2、3 等)。但是,当我尝试向构造函数添加参数以从调用它的类中获取此 id 时,出现上述错误。以下是两个相关文件:

app.component.ts

import { Component } from '@angular/core';
import {ClickComponent} from './click/click.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  display = false;
  clicks = [];

  toggleDisplay() {
    this.clicks.push(new ClickComponent(this.clicks.length + 1));
    this.display = !this.display;
  }
}

click.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-click',
  templateUrl: './click.component.html',
  styleUrls: ['./click.component.css']
})
export class ClickComponent implements OnInit {
  id;
  timeStamp;

  constructor(id: number) {
    this.id = 0;
    this.timeStamp = new Date();
  }

  ngOnInit() {
  }

}

如果我从 click 构造函数中删除参数并将 id 设置为 0,错误就会消失,因此它显然与我如何设置该构造函数有关,但我不明白我有什么问题m 对 Angular 来说是全新的。谢谢。

【问题讨论】:

  • 至少,您不会在 app.component.ts 中向new ClickComponent() 传递任何内容。它期望根据您在 click.component.ts 中指定的构造函数传递一个数字,例如 new ClickComponent(123)
  • 要记住的另一件事,要动态渲染组件,您需要使用Dynamic Component Loader。您将不能简单地实例化新组件并将它们添加到 DOM 以让它们呈现/解析/插值/等。
  • Angular 使用构造函数参数来解析dependencies。如果要设置在组件内部使用的值,请使用您直接初始化为任何值的局部变量,或使用@Input 从托管组件传入一个值。
  • @AlexanderStaroselsky 很抱歉混淆了。我正在传递一些东西,但出于故障排除目的将其取出。我编辑了我的帖子并将其添加回来。

标签: angular typescript


【解决方案1】:

我认为您不应该将 id 放在构造函数中,而应将 @Input() 放在 id 字段之前。
这就是参数以角度从父级传递给子级的方式。

已编辑:
如果您想知道如何将参数传递给动态创建的组件,请查看另一个线程: Angular2 - Pass values to a dynamic component created with ComponentFactory

【讨论】:

  • 那么当我在父级中创建一个新的 ClickComponent 时如何传递值呢?
猜你喜欢
  • 2017-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多