Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: Observable executes request multiple times

I am using observable in

service

getMembers(): Observable<any[]> {
return this._http.get('http://localhost/membership/main/getUsers')
  .map(response => response.json() );
}

component

members$: Observable<any[]>;
ngOnInit() {
 this.members$ = this._membersService.getMembers()
}

requests

-getUsers
-getUsers

both return the same JSON data

every time I load the page it returns a duplicate request. it is not about the hot and cold request. because both requests return the same response. but when I remove the observable, everything is ok. only one request

like image 947
edizonv Avatar asked Oct 05 '17 08:10

edizonv


2 Answers

I guess you are using the async pipe at two different places in the template. To avoid the re-execution of the request, you could use the share operator

import 'rxjs/add/operator/share';

members$: Observable<any[]>;
// I personally prefer to set observables in ctor
constructor() {
 this.members$ = this._membersService.getMembers().share();
}

More info about the operator can be found here

Another approach would be the use of the async pipe at a single place with the help of ng-container:

//template
<ng-container *ngIf="members$ | async as members">
   <span *ngIf="members.length === 0; else showMembers">No members!</span>
   <ng-template #showMembers>
     <div *ngFor="let member of members">{{member | json}}</div>
   </ng-template>
</ng-container>
like image 154
Jota.Toledo Avatar answered Sep 24 '22 23:09

Jota.Toledo


Update if you run across this in Angular 6+.

import { share } from 'rxjs/operators';
...
this._membersService.getMembers().pipe(share());

is the correct syntax now.

like image 36
Alex Avatar answered Sep 22 '22 23:09

Alex