我需要分享 Angular2 observables [英] Angular2 observables do I need to share

查看:54
本文介绍了我需要分享 Angular2 observables的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于搜索的表单输入.当用户在搜索输入中输入内容时,我需要调用 2 个单独的 api.这就是我想要实现的目标:

I have a form input for a search. When a user enters something in the search input I need to call 2 separate api's. This is what I'm trying to achieve:

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.

So my question is, how do I subscribe to valueChanges and call 2 different api's to fill 2 different arrays? With the code above, it works great on the initial search, but when I change the search text, only getListTwo is called.

推荐答案

每当一个源有多个订阅者,并且您希望这些订阅者从该源读取相同的值时(换句话说,您希望多播strong> 多个订阅者的源值),您应该share.

Whenever a source has several subscribers, and you want those subscribers to read the same value from that source (in other words you want to multicast the source values to several subscribers), you should share.

这里的意思是:sharedSource = this.myInput.valueChanges.debounceTime(500).distinctUntilChanged().share(),例如:

Here that means : sharedSource = this.myInput.valueChanges.debounceTime(500).distinctUntilChanged().share(), so for example :

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));
}

详细解释可以看一下此处 多播与冷流.

You can have a look at the detailed explanation here of multicast vs. cold streams.

这篇关于我需要分享 Angular2 observables的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆