0
votes

I'm calling method loadParticipant two times in two separated components, it's going almost in the same time, despite saving the Observable in the variable, api is called multiple times. This solution worked in AngularJs and Promises calls, but of course now I want use Observables :)

I tried to add debouncetime and share parameters after map

return (this.loadParticipantObservable = this.sharedEndpoints.getParticipant().map((response) => {
    this.loadParticipantObservable = null;
    return (this.participant = response);
})).share().debounceTime(1000);

actual code of loadParticipant method

public loadParticipant(): Observable<DTO<PersonModel>> {
    if (this.participant) {
        return new BehaviorSubject<DTO<PersonModel>>(this.participant);
    }

    if (this.loadParticipantObservable) {
        return this.loadParticipantObservable;
    }

    return (this.loadParticipantObservable = 
        this.sharedEndpoints.getParticipant().map((response) => {
            this.loadParticipantObservable = null;
            return (this.participant = response);
        }));
    }

example How I call loadParticipant Method

this.sharedService.loadParticipant().subscribe((response: DTO<PersonModel>) => {
            ...
     });

In the meantime, the Observable isn't null, code is coming into this condition and executes

 return this.loadParticipantObservable;

I checked it into debugger.

This is return me only observable but unfortunately this code calls the code lower this return what calls real endpoint from backend

1

1 Answers

0
votes

if I was in your shoes i would've tried to separate the fetching and visualizing logic in two, in other words a service with two methods:

  • methodI For retrieving and saving the data on the client (in variable inside the service) from the back end

  • methodII For getting the data (from the mentioned variable) in the components, that requires it

After that i will subscribe to methodII wherever i need to visualize the desired data, will make a call to the server in the nearest common parent component.

Take a look at this rxjs demo CodeSandbox, i think it will help you to understand the thing that I'm talking about :)

** Note: If you can afford it move to rxjs 5.5+ , because you will be able to use pipeable operators, which brings some benefits along , you can check this out on the topic: Pipeable operators article

** Note2: If you are working on medium-sized or bigger project, check out ngrx, because with ngrx, all headaches related to server calls and UI state management, will disappear.