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

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

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

类别组件.html

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

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

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


当前回答

您也可以将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;
 }
}

其他回答

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

@Input() inputValue: string;

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

基本上,这两种建议的解决方案在大多数情况下都很好。我对ngOnChange()的主要负面体验是缺乏类型安全性。

在我的一个项目中,我进行了一些重命名,之后一些魔术字符串保持不变,当然这个bug需要一些时间才能浮出水面。

setter没有这个问题:您的IDE或编译器会让您知道任何不匹配。

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

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

这是文件。

@Input() set categoryId(categoryId: number) {
      console.log(categoryId)
}

请尝试使用此方法。希望这有帮助

您可以在facade服务中使用BehaviorSubject,然后在任何组件中订阅该主题,当事件发生时触发对其的数据调用.next()的更改。请确保在销毁生命周期挂钩中关闭这些订阅。

data-api.facade.ts

@Injectable({
  providedIn: 'root'
})
export class DataApiFacade {

currentTabIndex: BehaviorSubject<number> = new BehaviorSubject(0);

}

某些组件

constructor(private dataApiFacade: DataApiFacade){}

ngOnInit(): void {
  this.dataApiFacade.currentTabIndex
    .pipe(takeUntil(this.destroy$))
       .subscribe(value => {
          if (value) {
             this.currentTabIndex = value;
          }
    });
}

setTabView(event: MatTabChangeEvent) {
  this.dataApiFacade.currentTabIndex.next(event.index);
}

ngOnDestroy() {
  this.destroy$.next(true);
  this.destroy$.complete();
}