angularrxjsangular2-http

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


Solution

  • 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>