【问题标题】:Why I can not get data from @input?为什么我无法从@input 获取数据?
【发布时间】:2019-03-04 19:31:04
【问题描述】:

在组件 A 的构造函数内部我使用以下代码:

public visitors: any[] = [];
 this.eventsService.view(this.activatedRoute.snapshot.params['id']).subscribe(response => {
      this.event = response.data.event;
      this.visitors = response.data.event.visitors;
});

组件A模板是:

<app-visitor-component [visitors]="visitors"></app-visitor-component>

为什么我在app-visitor-component 组件中的变量visitors 是空的,尽管存在数据:

@Input() visitors: IVisitor[];
 constructor() {
     console.log(this.visitors); // returns []
 }

【问题讨论】:

  • 如果您需要在ngOnInit() 时填充数据/长度,只需使用*ngIf 仅在visitors 具有数据/长度时渲染app-visitor-component。它总是出现在contructor/ngOnInit() 中的[],因为填充visitors 的异步调用仅在子组件的contructor/ngOnInit() 执行之后完成。否则,还有其他生命周期方法,例如 OnChanges,您可以在其中捕获对该 @Input 的更新。至少尝试在订阅以及contructor/ngOnInit 中放置一些console.log() 语句来可视化。

标签: angular


【解决方案1】:

ComponentA 模板visitor 中,如果您希望在子组件中绑定visitor 的值,最简单的做法是添加*ngIf 检查。

<app-visitor-component *ngIf="visitors.length" [visitors]="visitors"></app-visitor-component>

这会对visitors.length 的值进行真实检查,在服务调用返回值之前,该值将评估为false

我还建议您将服务调用移至eventsService.viewComponentAngOnInit 并移出构造函数。这也使ComponentA 更易于测试。


然后在子组件中为app-visitor

来自之前的回答@Input() value is always undefined

它将在ngOnInit 中初始化,而不是在构造函数中。 (请同时查看Angular Life Cycle Hooks documentation

您的代码使用OnInit

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

@Component({
    selector: 'app-visitor-component',
    templateUrl: ''
})
export class ComponentAppVisitor implements OnInit {

    @Input() visitors: IVisitor[];
    constructor() {
    }

    ngOnInit() {
        console.log(this.visitors);
    }
}

【讨论】:

  • 不,我试过 `ngOnInit() { console.log(this.visitors); } ` 它是空的 []
  • @OPV - 但事实并非如此。您正在constructor 中编写代码。数据将始终未定义,因为尚未发生绑定。
  • @OPV - 没有传递任何内容的另一个原因是,在您的服务调用返回值之前没有任何值。查看更新的模板代码,您可以添加*ngIf 检查以确保在父组件有值之前不会创建app-visitor 组件。
  • *ngIf="visitors" 还不够,您需要至少检查长度,因为它们默认为空数组[]
  • @AlexanderStaroselsky - 你说得对,我忽略了初始值分配。
【解决方案2】:

Angular 不会在创建组件后立即提供@Input 数据。 IE。 constructor()期间不可用。

如果您想在@Input 实际发送(并重新发送)时关闭,请使用 NgOnChanges:

import { Component, Input, OnChanges } from @angular/core';
@Component({
    selector: 'app-foo',
})
export class FooComponent implements OnChanges {
    @Input() visitors: IVisitor[];
    ngOnChanges() {
        if (this.visitors) {
            console.log(this.visitors)
            // do something with this.visitors
        }
    }
}

或者,您可以使用 getter/setter 在 Angular 发送某些内容时触发它:

    private _visitors: IVisitor[];
    @Input() public set visitors(val: IVisitor[]) {
        this._visitors = val;
    }
    // Also, guarantee to always return an array
    public get visitors(): IVisitor[] {
        if (this._visitors) {
            return this._visitors;
        }
        return [];
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-26
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    • 2011-08-06
    相关资源
    最近更新 更多