我有一个父组件(CategoryComponent)、一个子组件(videoListComponent)和一个ApiService。

我的大部分工作都很好,即每个组件都可以访问jsonapi,并通过可观测获取相关数据。

目前,视频列表组件只获取所有视频,我想将其过滤为特定类别中的视频,我通过@Input()将categoryId传递给孩子来实现这一点。

类别组件.html

<video-list *ngIf="category" [categoryId]="category.id"></video-list>

这是有效的,当父CategoryComponent类别发生更改时,categoryId值将通过@Input()传递,但我需要在VideoListComponent中检测到这一点,并通过APIService(使用新的categoryId)重新请求视频数组。

在AngularJS中,我会对变量进行$watch。处理此问题的最佳方法是什么?


当前回答

我只想补充一点,如果@Input值不是基元值,还有一个名为DoCheck的Lifecycle钩子很有用。

我有一个数组作为输入,所以当内容发生变化时,这不会触发OnChanges事件(因为Angular所做的检查是“简单”的,而且不深入,所以即使数组上的内容发生了变化,数组仍然是一个数组)。

然后,我实现了一些自定义检查代码,以决定是否要使用更改后的Array更新视图。

其他回答

我只想补充一点,如果@Input值不是基元值,还有一个名为DoCheck的Lifecycle钩子很有用。

我有一个数组作为输入,所以当内容发生变化时,这不会触发OnChanges事件(因为Angular所做的检查是“简单”的,而且不深入,所以即使数组上的内容发生了变化,数组仍然是一个数组)。

然后,我实现了一些自定义检查代码,以决定是否要使用更改后的Array更新视图。

在组件中使用ngOnChanges()生命周期方法。

ngOnChanges在数据绑定财产在检查视图和内容子项之前,如果至少其中一个已经改变了。

这是文件。

如果您正在处理使用@Input在父组件和子组件之间共享数据的情况,则可以使用生命周期方法检测@Input数据更改:ngOnChanges

 ngOnChanges(changes: SimpleChanges) {
    if (!changes.categoryId.firstChange) {
      // only logged upon a change after rendering
      console.log(changes.categoryId.currentValue);
    }
  }

我建议您注意为子组件实施的更改策略,因为某些性能原因,您应该添加ChangeDetectionStrategy.OnPush:

示例代码:

@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class VideoListComponent implements OnChanges {
  @Input() categoryId: string;

我会坚持采用@alan-c-s建议的方法,但需要做一些修改。首先,我反对使用ngOnChanges。相反,我建议将所有需要更改的内容移到一个对象下。并使用BehaviorSubject跟踪其变化:

  private location$: BehaviorSubject<AbxMapLayers.Location> = new BehaviorSubject<AbxMapLayers.Location>(null);

  @Input()
  set location(value: AbxMapLayers.Location) {
    this.location$.next(value);
  }
  get location(): AbxMapLayers.Location {
    return this.location$.value;
  }

<abx-map-layer
    *ngIf="isInteger(unitForm.get('addressId').value)"
    [location]="{
      gpsLatitude: unitForm.get('address.gpsLatitude').value,
      gpsLongitude: unitForm.get('address.gpsLongitude').value,
      country: unitForm.get('address.country').value,
      placeName: unitForm.get('address.placeName').value,
      postalZip: unitForm.get('address.postalZip').value,
      streetName: unitForm.get('address.streetName').value,
      houseNumber: unitForm.get('address.houseNumber').value
    }"
    [inactive]="unitAddressForm.disabled"
    >
</abx-map-layer>

您也可以将EventEmitter作为输入传递。不太确定这是否是最佳实践,尽管。。。

类别组件:

categoryIdEvent: EventEmitter<string> = new EventEmitter<>();

- OTHER CODE -

setCategoryId(id) {
 this.category.id = id;
 this.categoryIdEvent.emit(this.category.id);
}

类别组件.html:

<video-list *ngIf="category" [categoryId]="categoryIdEvent"></video-list>

在VideoListComponent.ts中:

@Input() categoryIdEvent: EventEmitter<string>
....
ngOnInit() {
 this.categoryIdEvent.subscribe(newID => {
  this.categoryId = newID;
 }
}