Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS and AngularJS HTTP - how can I achieve this?

I'm writing a small utility function that wrap a call to AngularJS http.get with the necessary authentication headers:

get(endpoint: string): Observable {
    var headers = new Headers();
    this._appendAuthentificationHeaders( headers, this.user.credentials);

    return this.http.get(endpoint, { headers: headers })
            .map(res => res.json());
}

The point here is that if this.user is null, the method will just crash. So I have three options:

  1. Return null and check that return value on every call...
  2. Throw an exception
  3. Find a way to also return an RxJS Observable object that will directly trigger the error handler.

I would like to implement the third method, as it would allow me unify this method's behavior: It always returns an observable no matter what happen.

  • Do you have an idea about how to do that?
  • Do I have to create a new Observable and kind of merge those two?
  • What can I do?
like image 685
Clement Avatar asked Oct 18 '22 15:10

Clement


1 Answers

If the user is null, you can simply return a raw observable that triggers an error:

if (this.user == null) {
  return Observable.create((observer) => {
    observer.error('User is null');
  });
}

(...)

or leverage the throw operator:

if (this.user == null) {
  return Observable.throw('User is null');
}

(...)

This way the second method of the subscribe method will be called:

observable.subscribe(
  (data) => {
    (...)
  },
  (err) => {
    // Will be called in this case
  }
);
like image 144
Thierry Templier Avatar answered Oct 27 '22 10:10

Thierry Templier