目前,我只是想实现以下目标: - 我有一个文本输入字段和一个按钮。单击按钮时,从输入中获取值(通过rxjs)。
以下是我的设置。目前有一个Observable的按钮单击,我有输入文本字段当前正在更新BehaviorSubject。我正在努力执行或解决的问题是,当一个值发送到点击流然后“切换”到输入流时,传递给订阅的是输入值。
目前传递给订阅的值始终是BehaviorSubject类型(当我不使用BS时最初是Observable)。
@Component({
selector: 'app-global-dashboard',
template: `
<input type="text" name="" id="new-country-input"
(keyup)="countryInput$.next($event.target.value)">
<button (click)="handleAddCountryClick()" id="add-country">Add
country</button>
<ul>
<li *ngFor="let tile of tiles">
{{tile.name}}
</li>
</ul>
`,
styleUrls: ['./global-dashboard.component.scss']
})
export class GlobalDashboardComponent implements OnInit, AfterViewInit
{
public countryInput = '';
public countryInput$ = new BehaviorSubject<string>('');
public tiles: object[];
constructor(private http: Http) {
this.tiles = [];
}
ngAfterViewInit() {
const button = document.querySelector('#add-country');
const addClick$ = Observable.fromEvent(button, 'click');
const inputAfterClick$ = addClick$
.map(() => this.countryInput$);
inputAfterClick$.subscribe((country) => {
console.log('country', country); // < This is always BS type rather than the underlying string
this.doRequest(country);
});
}
将地图更改为flatMap
const inputAfterClick$ = addClick$
.flatMap(() => this.countryInput$);
由于您使用的是BehaviouralSubject
,因此您需要获得的只是主题的当前值。无需切换流:
const addClick$ = Observable.fromEvent(button, 'click');
addClick$.subscribe(()=>{
//this will give you the current value of your behavioural subject
console.log(this.countryInput$.value);
})
如果你想以更“反应”的方式获得输入值,你最好使用Reactive Forms