In my service, I have a function which gets some data from the server. Several parts of my application call this function at init time. And what I'd like to do is that: if there is already one request being sent, the other wait for its response (they don't need to make their own request).
So my code is:
@Injectable()
export class UserService implements OnInit {
  ngOnInit(){
        this.getUserInformations();
  };
  public getUserInformations(forceRefresh?: boolean): Observable<Object>{
        if(this.userInformationsLastObservable == null) {
            console.log('Making a request'); // called only once at init
            this.userInformationsLastObservable = this.http.get(this.baseUrl + "informations")
            .map((result: Response) => {
                console.log('map is called'); // called 5 times at init
                let userInformations = result.json();
                /* So future calls will perform a new request */
                this.userInformationsLastObservable = null;
                return userInformations;
            });
        }
        return this.userInformationsLastObservable;
    };
}
And several components call it this way:
@Component({
  selector: 'app-leaderboard',
  templateUrl: 'leaderboard.component.html',
  styleUrls:  ['leaderboard.component.css'],
  providers: []
})
export class LeaderboardComponent implements OnInit
{
  ngOnInit(){
      this.userService.getUserInformations().subscribe((userInformations) => {
        this.userInformations = userInformations;
        /* this function does not make any call to the User service */
        this.refresh();
      }, () => {
        this.isLoading = false;
      });
    };
}
The problem is: from the Network panel of the console, I see that 5 requests are sent at init time. And 'map is called' is printed 5 times too, whereas 'Making a request' is only called once.
What am I doing wrong ?


 
     
    