Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why to use observables instead of Ajax?

Why should I use an HTTP observable method like this:

this.http.get("MyURL")
         .subscribe(
            (_url: any) => {
                //TODO My job
            },
            (error: any) => {
                //TODO My job
            },
            () => {
                //TODO My job
            });

Instead of use an AJAX method like this:

$.ajax({
    url: "MyURL",
    success: function (result) {
        //TODO My job
    },
    error: function () {
        //TODO My job
    }
});

I mean, what are the benefits and harms?

like image 766
fba_pereira Avatar asked Nov 30 '17 11:11

fba_pereira


3 Answers

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.

like image 107
realappie Avatar answered Oct 21 '22 22:10

realappie


Please read the below link for better information :

https://angular-2-training-book.rangle.io/handout/observables/observables_vs_promises.html

What it seems like it is used majorly because Observables can define both the setup and teardown aspects of asynchronous behavior.

like image 2
Danish Avatar answered Oct 22 '22 00:10

Danish


Fundamentally, they're the same thing. It's really just the implementation and usage that differ, so it becomes a matter of preference really.

Observables (which generally refer to the "RxJS" library, though not always) generally have a subscribe() method which lets them listen for changes, and have hooks for onNext() (something happened), onError() (something went wrong), and onComplete() (all done).

jQuery's AJAX syntax is a more "classic" callback structure, where you call the function and provide it with callbacks directly. It also has another syntax which allows you to add them as subsequent functions (.done() and the like).

When talking about JavaScript specifically though, nowadays I would argue that the Promise syntax is the most popular, as it is standardized in ECMAScript 6 and is natively supported by most browsers nowadays. fetch() is a native implementation of doing AJAX requests with Promise syntax.

At the end of the day, neither is particular better or stronger at the end of the day, and it really just boils down to personal preferences and past experience (for example, Observables are popular with developers who have Java experience, since Observables are used pretty frequently in Java).

Out of the three, only the Promise one has any real advantage, which is that it is natively supported by modern browsers (whereas the other two require a third-party library). But if you're already using a third-party library for something else, that's not a huge benefit.

like image 2
samanime Avatar answered Oct 21 '22 22:10

samanime