Angular2 可观察共享不起作用 [英] Angular2 observable share is not working

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

问题描述

Angular2 Observable 共享不起作用并且重复的 http 调用正在进行

Angular2 Observable share is not working and duplicate http calls going

BuildingService.ts

@Injectable()
export class BuildingService {

constructor(private http: Http){       
  }

buildings$: Observable<Building[]>;
this.buildings: Building[];

getData() : Observable<Building[]>{
     this.buildings$ = this.http.get('http://localhost:8080/buildings').share().map(this.extractData);
     this.buildings$.subscribe(buildings => this.buildings = buildings);
     return this.buildings$;
  }

 private extractData(res: Response) {
    let body = res.json();
    return body;
} 

}

component1.ts

export class component1 {
constructor( private  buildingService: BuildingService) {}

this.subscription = this.buildingService.getData()
            .subscribe(buildings => console.log(buildings),
            error =>  this.errorMessage = <any>error);
}

component2.ts

export class component2 {
constructor( private  buildingService: BuildingService) {}

this.subscription = this.buildingService.getData()
            .subscribe(buildings => console.log(buildings),
            error =>  this.errorMessage = <any>error);
}

share 不起作用,多个 http 调用正在进行.甚至我也尝试过此链接

share is not working, multiple http calls are going. Even I tried code from this link

但没用.

有人可以告诉我如何避免使用 Angular Observable 进行重复的 http 调用吗?

Can somebody please let me know how to avoid duplicate http calls with Angular Observable?

推荐答案

我认为这只是对 share() 的作用的误解.

I think this is just misunderstanding of what share() does.

当您调用 this.buildings$.subscribe(...) 时,由于 share() 运算符,它会生成一个 ConnectableObservable紧随其后的是 connect().

When you call this.buildings$.subscribe(...) it makes a ConnectableObservable thanks to share() operator which is immediately followed by connect().

如果您在 HTTP 请求未决时进行另一个订阅,它只会将另一个观察者添加到 ConnectableObservable 并且当响应准备好时,它将被发送到两个观察者.但是,如果您让 this.buildings$ 完成,然后再次订阅,它将发出另一个 HTTP 请求,因为 ConnectableObservable 未连接到其源.

If you make another subscription while the HTTP request is pending it will just add another Observer to the ConnectableObservable and when the response is ready it'll be sent to both Observers. However if you let this.buildings$ to complete and after that you subscribe again it'll make another HTTP request because the ConnectableObservable is not connected to its source.

你想要的是重播从来源.您很可能还希望附加 take(1) 以正确完成链.

What you want instead is .publishReplay(1).refCount() (or shareReplay(1) since RxJS 5.4.0) that replays the last item emitted from the source. Very likely you'll also want to append take(1) to properly complete the chain.

这篇关于Angular2 可观察共享不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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