@Input() 值未定义

@Input() value is undefined

我创建了采用 @Input() 值的组件,但我总是得到 undefind。 这是我的代码:

parent.html

<added-item
      [minItemValueLength]="minItemValueLength"
      [maxItemValueLength]="maxItemValueLength"
      [listOfItems]="listOfItems"
  ></added-item>

children.ts

export class AddedItemComponent implements OnInit, OnChanges{

  @Input() minItemValueLength: number;
  @Input() maxItemValueLength: number;
  @Input() listOfItems: string[];

  ngOnInit() {
    console.log(this.minItemValueLength)      // return 3 
    console.log(this.listOfItems)             // return undefined
  }
}

parent.ts

export class LocationsTabComponent implements OnInit {
  listOfItems: string[];
  minItemValueLength = 3;
  maxItemValueLength = 15;

  public ngOnInit(): void {
    this.locationService.getLocations().subscribe((locations) => {
      this.getLocationsList();
      console.log(this.listOfItems)    // return Array(6)
    });
  }
  private getLocationsList() {
    this.listOfItems = this.locations.map((location: Location) => location.name);
    console.log(this.listOfItems)    // return Array(6)
  }
}

如果我在儿童中使用 ngOnChanges() 而不是它首先输出我:

data undefined 然后:

data Array(6)

如何在 onInit 中获取此值?

非常感谢任何帮助!

这是因为你分配

listOfItems = ...

在异步回调方法中。

如果要检测变化,需要实现onChanges接口,实现相应的hook方法。

export class AddedItemComponent implements OnInit, OnChanges{

    @Input() minItemValueLength: number;
    @Input() maxItemValueLength: number;
    @Input() listOfItems: string[];

    ngOnInit() {
        console.log(this.minItemValueLength)      // return 3 
        console.log(this.listOfItems)             // return undefined
    }
    
    ngOnChanges(changes: SimpleChanges): void {
        if (changes.listOfItems) {
            console.log(this.listOfItems)
        }
    }

}

由于您订阅了位置,您可以使用 async 等待响应完全解析,否则您必须实现 OnChanges 接口。

public async ngOnInit(): void {
await this.locationService.getLocations().toPromise().then((locations) => {
  this.getLocationsList();
  console.log(this.listOfItems)    // return Array(6)
});
}
private getLocationsList() {
  this.listOfItems = this.locations.map((location: Location) => location.name);
  console.log(this.listOfItems)    // return Array(6)
}

该值并不总是 undefined 仅在创建组件时出现,这是因为您是这样传递的。

进程:

  1. Parent 正在创建,ngOnInit 正在启动。
  2. ngOnInit 有 Observable\Promise\Async 方法,这意味着我们不等待响应,因此该值仍未定义。
  3. Child 组件已创建并执行 ngOnInit。值仍未定义。
  4. Observable\Promise\Async 方法现在终于完成了,您创建的自定义回调现在分配了值,并将值传递给 child 组件。 所以当然childngOnInit不会接受,因为组件已经创建了。

有几个解决方案:

  1. *ngIf="listOfItems" 放在 added-item 上。
  2. 将 Parent 修饰为 async ngOnInit,将:.subscribe 更改为 .toPromise 例如:await this.locationService.getLocations().toPromise...,现在 parent ngOnInit将等待回复。