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

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

问题描述

Angular2可观察的共享不起作用,重复的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);
}

共享不起作用,正在进行多个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.

您想要的是.publishReplay(1).refCount()(或自RxJS 5.4.0起为shareReplay(1)),它可以重播从源发出的最后一个项目.您很有可能还希望附加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天全站免登陆