1
votes

I come from a synchronous programming background and I am having a hard time understanding observables.

Here is an extract of my service/provider (Ionic 2 project)

return this.http.get(`${this.serverApi}`)
  .map(res => <Response[]>res.json());

and I will subscribe to that from the LoginPage. I have several questions regarding this.

  1. Does the above code return an observable/ observer even if I didn't declare it as such?

  2. The response is JSON. How do I do some checking/processing of the JSON and perform some action like if

    res.auth_token==true
    

    then do

     localStorage.setItem(res.auth_token)
    

    I believe it should be done in the provider class. Just a typical hint/example will be awesome.

  3. Does the request actually happen when it hits the subscribe method?

  4. Creating and returning Observable from Angular 2 Service mentions Subject and ReplaySubject. Should I use them instead?

1
1. It returns the result of Observable.map, which is itself an observable. 2. Add another .map or do it in the current one. 3. The response is made when you .subscribe, yes, not just when you return the observable. 4. I don't see a need to do that in your current code, but... maybe?jonrsharpe

1 Answers

3
votes
  1. The code will return an Observable

  2. You can change the callback body to a block and add as much code as you want

return this.http.get(`${this.serverApi}`)
  .map(res => {
     let x = <Response[]>res.json();
     // do something with x
     res.auth_token == true;
     return res; // with a block body an explicit`return` is required
  });
  1. Yes, calling .subscribe() will execute the http.get() and then all subsequent operators when the response arrives. Without .subscribe() nothing will happen.

Note: Some Angular APIs expect an Observable, in this case you must not call subscribe() because subscribe() returns a Subscription, not an Observable.

  1. it depends what you try to accomplish. If you use http.get(), you already get an observable and there is no need for Subject, ReplaySubject, or any of the other possibilities.