我有一个父组件(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在父组件和子组件之间共享数据的情况,则可以使用生命周期方法检测@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;
如果不想使用ngOnChange实现og onChange()方法,还可以通过valueChanges事件等订阅特定项的更改。
myForm = new FormGroup({
first: new FormControl(),
});
this.myForm.valueChanges.subscribe((formValue) => {
this.changeDetector.markForCheck();
});
markForCheck()writen,因为在这个声明中使用:
changeDetection: ChangeDetectionStrategy.OnPush
您可以在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();
}