我有一个用于搜索的表单输入。当用户在搜索输入中输入内容时,我需要调用 2 个单独的 api。这就是我要实现的目标:
myInput: new FormControl();
listOne: Observable<string[]>;
listTwo: Observable<string[]>;
ngOnInit(){
this.listOne = this.myInput.valueChanges
.debounceTime(500)
.distinctUntilChanged()
.switchMap(myInput => this._service.getListOne(myInput));
this.listTwo = this.myInput.valueChanges
.debounceTime(500)
.distinctUntilChanged()
.switchMap(myInput => this._service.getListTwo(myInput));
}
所以我的问题是,如何订阅 valueChanges 并调用 2 个不同的 api 来填充 2 个不同的数组?使用上面的代码,它在初始搜索时效果很好,但是当我更改搜索文本时,只会调用 getListTwo。
最佳答案
每当一个源有多个订阅者,并且您希望这些订阅者从该源读取相同的值(换句话说,您希望将源值多播给多个订阅者),您应该分享
。
这意味着:sharedSource = this.myInput.valueChanges.debounceTime(500).distinctUntilChanged().share()
,例如:
myInput: new FormControl();
listOne: Observable<string[]>;
listTwo: Observable<string[]>;
ngOnInit(){
this.listOne = sharedSource
.switchMap(myInput => this._service.getListOne(myInput));
this.listTwo = sharedSource
.switchMap(myInput => this._service.getListTwo(myInput));
}
可以看看详细的解释here多播与冷流。
关于javascript - Angular2 observables 我需要分享吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39359427/