5

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

3
  • first that you need to fix is a data type of members$: any[]. Because your service when map data return data and not Observable Commented Oct 5, 2017 at 8:32
  • as I understood you are using members$|async in template 2 times Commented Oct 5, 2017 at 8:41
  • @Danil, wow thanks, I call the async twice because I need to add a condition if there is no value *ngIf="(members$ | async)?.length>0; else noMember, then inside the condition I loop another members$ | async that cause the duplicate request, how am I suppose to validate if not empty before I loop without duplicating request Commented Oct 5, 2017 at 8:54

2 Answers 2

12

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>
Sign up to request clarification or add additional context in comments.

2 Comments

I am looping the data in table row.. thats why i dont use the 2nd aporoach you said.. i dont know where to put that if condition inside table row. Maybe ill try the share function tomorrow thanks
@edizonv you would need to wrap the elements that use the 'members' value inside of a ng-container. Let me now if this helped.
2

Update if you run across this in Angular 6+.

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

is the correct syntax now.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.