-2

In angular, we have Observables which makes easier in handling HTTP requests. Along with there are functions like

map(), subscribe(), pipe()

and I do not know much.

The problem I am facing here is, when to use this function, which is best suited for which situation? I am not at all following these.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
Anil
  • 1,748
  • 8
  • 32
  • 67

1 Answers1

2

This is a broad topic (could cover all of RxJS) but here are the basics.

Observables are objects that can asynchronously emit a value, and notify users when there is an error or no more objects will be emitted. You register to get values from an observable by using subscribe (ok, not technically the only way but its the usual and most basic one). They enable this sort of flow:

  1. Observable created
  2. You subscribe and print the emitted value (obs.subscribe(v => console.log(v))
  3. Time passes, stuff happens (the method where subscribe was called has long since returned)
  4. The observable emits "Hello World"
  5. The callback you passed in subscribe is called and "Hello World" is printed to the console.

These are useful in HTTP requests (through HttpClient) in particular because HTTP requests are inherently asynchronous. You put bytes on the wire and at some point bytes will come back. You don't want your website to freeze up while you wait though. Hence; the HttpClient methods return observables that you subscribe to in order to retrieve the request result.

As far as the methods you mentioned (map, filter, pipe) they are just helper methods that allow you to do various things to an observable as it emits. There are lots more and you can find a lot more about each in the documentation. A quick summary of map and filter (haven't used pipe):

  • map takes a source observable and allows you to transform it into a different type of observable.
  • filter creates an observable that only emits items from the source observable if a predicate is satisfied.
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117