Perfect Way Of Making Http Calls In Angular

95 Views Asked by At

In the context of the discussion at https://stackoverflow.com/a/35043309/19365092, it is advisable to avoid using the subscribe method for HTTP calls. The reason is that while it is true that subscribe unsubscribes automatically upon successful API calls, it does not handle errors gracefully. In the event of an API call failure, the observer will remain subscribed, leading to potential memory leaks.

Here's an example of using subscribe for reference:

subscribe({
    next: (v) => console.log(v),
    error: (e) => console.error(e),
    complete: () => console.info('complete') // This is only called if the API call was successful
})

Instead, it is recommended to use the firstValueFrom and lastValueFrom methods from RxJS, as they provide robust handling for all scenarios. Both of these methods effectively convert an observer into a promise. Below is an example of how they work:

source.subscribe({
    next: (value) => {
        _value = value;
        _hasValue = true;
    },
    error: reject,
    complete: () => {
        if (_hasValue) {
            resolve(_value);
        } else if (hasConfig) {
            resolve(config!.defaultValue);
        } else {
            reject(new EmptyError());
        }
    },
});

This code snippet represents the internal workings of lastValueFrom. In the event of an error, it appropriately rejects the promise, ensuring proper error handling.

In summary, it is advisable to use firstValueFrom and lastValueFrom for HTTP calls when working with RxJS, as they offer better control and handling of both success and error scenarios.

Perfect Way Of Making Http Calls In Angular

0

There are 0 best solutions below