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 is not working, multiple http calls are going. Even I tried code from this link
but no use.
Can somebody please let me know how to avoid duplicate http calls with Angular Observable?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…