Why would you use an external library to do something angular is already capable of? Why would you actually use jQuery at all in combination with angular?
I think a better title for your question would have been, why use observables at all. I have had the same question when I started with angular, but after working with angular for over a year and having worked a lot with observables and rxjs
over that period of time I have learned the following.
1- You cannot cancel promises
Lets say somebody goes to screen A, and you fetch some data like so.
fetch(/** some end point */)
.then(res => res.json())
.then(() => {
// Handle the request here
});
And by the time you are able to handle the request, the user leaves screen A. In most cases that is not a big deal, but because you want to do things the best way possible you would preferably cancel the handling of the request. With native promises, that's simply impossible. Read this article for great explantion on this
With observables, this becomes trivial. You can unsubscribe from an observable and that will ensure no unnecessary code is executed.
Pro tip: In angular you would do this in the ngOnDestroy
life cycle of a component.
2 - Native promises have 2 methods, rxjs has many many more.
If you are using the native promises implementation, the only things you can do are then
and catch
(on a promise instance). This might seem more than enough, but with rxjs you can do many many more things.
Example
Lets say your /article/:id
end point sometimes returns empty values because there is no article found. In promises your code will look something like this.
fetch('/article/5')
.then( res => res.json())
.then( res => {
if ( res !== undefined) {
// do something!
}
});
In rxjs this looks much cleaner, in the case of wanting to only do something with the data if its there. This might not seem as a big improvement, but in production you will find yourself wanting to do much much more than filtering out undefined values.
this.http.get("MyURL")
// p.s this line of code might not be needed depending on ur
// angular version
.map( res => res.json())
.filter( res => res !== undefined)
.subscribe(res => {
// Do something!
});
My advice for you would be to use toPromise
wherever you are doing something simple, and to gradually use more and more rxjs operators once you need them. map
, filter
and takeUntil
would be a good starting point.
I could go on showing you things you can do with rxjs that are hard to implement with promises, but there are lots of articles out there that do a better job than me explaining that.
TLDR
You can write cleaner asynchronous code and do more things with less code.
http
is a provider / service and not a directive :)