-1

Which is the best way to manage subscribers on a Angular HTTP request in this case:

I have button that performs a get request and then prints the result:

Template

<button type="button" class="btn btn-primary" (click)="helloWorld()">Mod1</button>

Component

constructor(private heroService: HeroService) { }

helloWorld() {
    this.heroService.getUser().subscribe(data => console.log(data));
}

Service

constructor(private _http: HttpClient) { }

getUser() {
    return this._http.get("https://randomuser.me/api/");
}

The mainly problem here is, every time I press the button a new subscription is created, causing memory leaks and poor performance over time due to unused listeners.

How may I implement a multiple get request without affect the application performance?

  • Im pretty sure that your code isnt causing any sort of mem. leaks. Why dont you just check inside of the helloWorld method if the HTTP call was already made? eg through a flag value – Jota.Toledo Jun 01 '18 at 17:39

1 Answers1

1

In your component you may have an user attribute that you check before calling the service:

user: any;

constructor(private heroService: HeroService) { }

helloWorld() {
    if (!this.user) {
        this.heroService.getUser().subscribe(data => this.user = data);
    }
}

PS: Http calls that run once didn't cause memory leaks or performance issues, so you don't necessarily need to unsubscribe from them. It's stream open subscriptions that can have a negative impact on you app performance. (example: form control valueChanges)

Mehdi Benmoha
  • 3,694
  • 3
  • 23
  • 43
  • what's with the `user` property how would it help? – Vikas Jun 01 '18 at 16:11
  • The user attribute is where you store your user response from the random API. It helps by preventing another call to the API when response already fetched. – Mehdi Benmoha Jun 01 '18 at 16:12
  • That's quite evident how do you suggest that it will prevent memory leak as OP has mentioned, what if OP really want to fetch new record on `click` event your approach would not allow making any further request to API. – Vikas Jun 01 '18 at 16:15
  • I updated my answer, HTTP calls didn't cause memory leaks ! – Mehdi Benmoha Jun 01 '18 at 16:16
  • what if OP wants to make Multiple `Http` calls? your approach would fail. – Vikas Jun 01 '18 at 16:17
  • The thing that's causing performance issues isn't Http calls ! Browsers are used to them now in 2018 hahaha. HttpClient is also unsubscribing automatically after request completion. I think that the performance issue is somewhere else. – Mehdi Benmoha Jun 01 '18 at 16:22
  • @Vikas if you think that OPs code could cause a memory leak, you have no idea what you are talking about – Jota.Toledo Jun 01 '18 at 17:42
  • @Jota.Toledo Keep the memory leak aside I was mistaken what about multiple `Http` request will this code let OP make multiple requests to `API` – Vikas Jun 01 '18 at 17:44