javascript - Angular2 observables 我需要分享吗

标签 javascript angular rxjs

我有一个用于搜索的表单输入。当用户在搜索输入中输入内容时,我需要调用 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/

相关文章:

javascript - 跨域 Ajax 抛出 No 'Access-Control-Allow-Origin' header 错误但网络选项卡显示响应数据

选择 Angular 自动完成输入并模糊事件竞争条件

angular - 如何在 Angular/rxjs 中使用异步管道时传递参数?

Angular 2 - 倒数计时器

angular - 如何在 RxJS 的 GroupBy 中使用分组键,

javascript - RxJS Node 在订阅下一个序列之前等待 observable 完成

javascript - react 路由器不使用参数

javascript - 从 Javascript 函数加载和引用 DOM 元素

java - 我无法访问外部 javascript 文件中的 freemarker 变量

Angular 路由动画 : Plays once on refresh