2

Let's say I have a function like this in a provider:

getAll(): Observable<CarModel[]> {
    return this.http.get<CarModel[]>(this.carUrl);
}

And in a component I have a function that uses this function of the provider:

getCars() {
        const that = this;
        this.carService.getAll().subscribe(function(cars) {
            that.factoryService.setCars(cars);
            this.unsubscribe();
        });
    }

Is it okay to replace that with a function that uses the take operator to avoid having to call unsubscribe()?

getCars() {
        const that = this;
        this.carService.getAll().take(1).subscribe(function(cars) {
            that.factoryService.setCars(cars);
        });
    }

I wonder if this can have any unexpected or unwanted behavior when used with Angular's Httpclient's methods? I've never seen the Angular's Httpclient used like that - that's why I'm asking.

GeForce RTX 4090
  • 3,091
  • 11
  • 32
  • 58

2 Answers2

6

The HttpClient calls complete on the stream after a request completes. An Observable that calls complete signals that no more values will be emitted and so any subscribers will not receive any more values. This means that there is no reason to unsubscribe or use take with an http request.

getAll(): Observable<CarModel[]> {
  return this.http.get<CarModel[]>(this.carUrl); // <- Emits once and completes
}

Checkout this section from the docs. Note:

An observable from HttpClient always emits a single value and then completes, never to emit again.

Teddy Sterne
  • 13,774
  • 2
  • 46
  • 51
1

As you, I've never seen like this before.

I used to convert all http requests observables into promises:

In the MDN site, you can find this: The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

this.carService.getAll()
        .toPromise()
        .then((cars) => {
            that.factoryService.setCars(cars);
        }).catch((error) => {
            console.error(error);
        });
Thomaz Capra
  • 985
  • 9
  • 21