【问题标题】:Subscribing to the same observable (shared) from different components with params使用参数从不同组件订阅相同的 observable(共享)
【发布时间】:2017-12-07 18:12:48
【问题描述】:

我在同一页面上有两个组件。每个组件都显示有关订阅来自带有参数的服务的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 调用。

【问题讨论】:

    标签: angular rxjs angular-services


    【解决方案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();
    
        }
    

    【讨论】:

    • 使用void 将不起作用。我现在如何在组件中获取数据?
    • 是的,刚刚发现错字。好的,我明白你想解释什么,但我怎样才能得到组件中的数据。 this.mainService$ 现在是 undefined..
    猜你喜欢
    • 1970-01-01
    • 2018-06-03
    • 2018-03-10
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    相关资源
    最近更新 更多