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

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

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

类别组件.html

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

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

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


当前回答

您还可以在父组件(CategoryComponent)中的更改时触发一个可观察值,并在子组件的子属性中执行您想要执行的操作。(视频列表组件)

服务.ts

public categoryChange$ : ReplaySubject<any> = new ReplaySubject(1);

类别组件.ts

public onCategoryChange(): void {
  service.categoryChange$.next();
}

视频列表组件.ts

public ngOnInit(): void {
  service.categoryChange$.subscribe(() => {
   // do your logic
  });
}

其他回答

可以使用ngOnChanges()生命周期方法

@Input() inputValue: string;

ngOnChanges(changes: SimpleChanges) {
    console.log(changes['inputValue'].currentValue);
}

如果您正在处理使用@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;

您还可以在父组件(CategoryComponent)中的更改时触发一个可观察值,并在子组件的子属性中执行您想要执行的操作。(视频列表组件)

服务.ts

public categoryChange$ : ReplaySubject<any> = new ReplaySubject(1);

类别组件.ts

public onCategoryChange(): void {
  service.categoryChange$.next();
}

视频列表组件.ts

public ngOnInit(): void {
  service.categoryChange$.subscribe(() => {
   // do your logic
  });
}

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

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

这是文件。

在函数签名中使用SimpleChanges类型时,我在控制台、编译器和IDE中都遇到了错误。为了防止错误,请在签名中使用any关键字。

ngOnChanges(changes: any) {
    console.log(changes.myInput.currentValue);
}

编辑:

正如Jon在下面指出的,当使用括号符号而不是点符号时,可以使用SimpleChanges签名。

ngOnChanges(changes: SimpleChanges) {
    console.log(changes['myInput'].currentValue);
}