[英]How to avoid using 'any' when using FromEvent RxJS with Angular to subscribe to input tag value changes?
I cannot define specific type when using FromEvents
from RxJS.使用
FromEvents
中的 FromEvents 时,我无法定义特定类型。 When I pipe the 'keyup' event and map it to get the inputed value, I can only use (e: any => return (e.target.);value;)
.当我 pipe 'keyup' 事件和 map 获取输入值时,我只能使用
(e: any => return (e.target.);value;)
。 Even though the browser's debuggers identifies the e
as a KeyboardEvent
, if I define e: KeyboardEvent
I get an error stating that "e does not contain property target".即使浏览器的调试器将
e
识别为KeyboardEvent
,如果我定义e: KeyboardEvent
,我会收到一条错误消息,指出“e 不包含属性目标”。 The current code works, however, since I am new to RxJS + Angular, and the community always advise to avoid using any
, so I wonder what can I do to avoid using it in this situation?但是,当前代码有效,因为我是 RxJS + Angular 的新手,并且社区总是建议避免使用
any
,所以我想知道在这种情况下我该怎么做才能避免使用它?
Component.ts组件.ts
import { TagInterface } from './../../../interfaces/tag/tag-interface';
import { Component, OnInit, Output, EventEmitter, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { debounceTime, distinctUntilChanged, filter, map } from 'rxjs/operators';
import { fromEvent, Observable } from 'rxjs';
@Component({
selector: 'app-tag-search-bar',
templateUrl: './tag-search-bar.component.html',
styleUrls: ['./tag-search-bar.component.scss']
})
export class TagSearchBarComponent implements OnInit,AfterViewInit {
@Output() tags = new EventEmitter<TagInterface[]>();
@ViewChild('tagInput') tagInputChild!: ElementRef;
mappedAndFilteredInput!: Observable<any>;
eventKeyUp! : Observable<any>;
constructor() { }
ngOnInit(): void {
}
ngAfterViewInit() {
this.eventKeyUp = fromEvent(this.tagInputChild.nativeElement, 'keyup');
this.mappedAndFilteredInput = this.eventKeyUp.pipe(
map((e: any) => {
return (e.target!).value;
}),
debounceTime(100),
distinctUntilChanged(),
filter(value => (value != "" && value != undefined))
);
this.mappedAndFilteredInput.subscribe(
value => console.log(value),
error => console.log(`error: ${error}`),
() => console.log('completed maping and filtering tag input term'));
}
}
HTML HTML
<div class="input-group-prepend">
<span class="input-group-text">
<i class="far fa-filter"></i>
</span>
</div>
<input #tagInput type="text" class="filter-tag-list">
Here's the type-safe way to get the target
from a KeyboardEvent
这是从
KeyboardEvent
获取target
的类型安全方法
fromEvent<KeyboardEvent>(document.documentElement, 'keyup').subscribe(e => {
const [target] = e.composedPath()
console.log(target)
})
However, in your case it would be simpler to just do但是,在您的情况下,这样做会更简单
fromEvent(this.tagInputChild.nativeElement, 'keyup').subscribe(_ => {
console.log(this.tagInputChild.nativeElement.value)
})
Or better still use a form control, and listen to valueChanges on the form control.或者最好还是使用表单控件,并在表单控件上监听 valueChanges。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.