使用params订阅来自不同组件的相同可观察(共享)

时间:2017-12-07 08:21:35

标签: angular rxjs angular-services

我在同一页面上有两个组件。每个组件都显示订阅来自带有参数的服务Observable的订单的内容。

服务:

getOrders(url: string, query: string) : Observable<any> {
        return this.http.get(url + "&" + query, this.options)
                        .map((res:Response) => res.json())
                        .catch((error:any) => Observable.throw(error || 'Server error'))
                        .share();

    }

组件1:

    Observable.combineLatest(this.behaviorsubject1,this.behaviorsubject2)
    .subscribe((res)=>{
                this.combineLatestStream = res;
                this.selectedOrganization = this.combineLatestStream[1];

                this.mainService$ = this.orderService.getOrders(this.settings.backend.orders, "organization_id="+this.selectedOrganization.organization_id);
                this.mainService$.subscribe(result => {
                //call 1
                });

    });

组件2:

  this.aservice.stuff.subscribe((res) => {
    this.selectedOrganization = res;
    this.mainService$ = this.orderService.getOrders(this.settings.backend.orders, "organization_id="+this.selectedOrganization.organization_id+"&status=1");
    this.mainService$.subscribe((val) => {
       //call 2
    })
  })

在第一个组件中,我获得了所有订单;在第二个组件中,我只得到其中的一些(基于一些参数);都是mainService$。我将有更多需要订阅此服务的组件。共享服务无效。还有其他方法吗?

我也试过publishReplay(1).refCount()。我不希望有多个API调用。

1 个答案:

答案 0 :(得分:1)

http observable在订阅后完成,如果您希望通知所有订阅者,则需要使用BehaviorSubject并调用getOrders behaviorSubject.next():

示例:

behaviorSubject = new BehaviorSubject(<Orders[]>{}) 

getOrders(url: string, query: string) : void {
        this.http.get(url + "&" + query, this.options)
                        .map((res:Response) => res.json())
                        .catch((error:any) => Observable.throw(error || 'Server error'))
                        .do((orders) => behaviorSubject.next(orders))
                        .subscribe();

    }