我正在努力订阅 Angular 4 中的选择下拉更改。我的searchType
变量的更改仅在test()
通过单击事件调用函数后可见,但我需要 Angular 立即订阅更改。
边注:
- 我正在订阅过滤器管道。
- 模块中提供了服务,因此在同一个实例上工作
App.component.html
<select name="searchType" id="searchType" #searchType>
<option value="movie_title"> movie title</option>
<option value="director">director</option>
<option value="actor"> actor</option>
</select>
应用组件.ts
@ViewChild('searchType') select: ElementRef;
searchType: number;
constructor(private service: ServiceService) {}
ngOnInit() {
this.searchType = this.select.nativeElement.options.selectedIndex;
this.service.sendSearchType(this.searchType);
}
test() {
this.searchType = this.select.nativeElement.options.selectedIndex;
this.service.sendSearchType(this.searchType);
}
服务.service.ts
searchType = new Subject<number>();
sendSearchType(id: number) {
this.searchType.next(id);
}
getSearchType(): Observable<number> {
return this.searchType.asObservable();
}
最后filter.pipe.ts订阅更改
searchType: number;
private subscription: Subscription;
constructor(private service: ServiceService) {
this.service.getSearchType().subscribe(
(id) => (this.searchType = id)
);
}
transform(value: any[], filter: string): any[] {
filter = filter ? filter.toLocaleLowerCase() : null;
return filter ? value.filter(
(product) =>
this.auxiliaryFunction(product, filter)
) : value;
}
auxiliaryFunction(product, filter) {
if (this.searchType === 2) {
return (product.actor.toLocaleLowerCase().indexOf(filter) !== -1)
} else if (this.searchType === 1) {
return (product.director.toLocaleLowerCase().indexOf(filter) !== -1)
} else {
return (product.movie.toLocaleLowerCase().indexOf(filter) !== -1)
}
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
我哪里做错了 ?将不胜感激任何解决方案。