RxJS and AngularJS HTTP - how can I achieve this?

I am writing a small utility function that completes the 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 work. Therefore, I have three options:

  • Returns null and checks that the return value for each call ...
  • Throw an exception
  • Find a way to return an RxJS Observable object that will directly trigger the error handler.

I would like to implement the third method, as this would allow me to unify the behavior of this method: it always returns the observable, no matter what happens.

  • Do you have any idea how to do this?
  • Should I create a new Observable and combine these two?
  • What can I do?
+5
source share
2 answers

If user is null , you can simply return the raw observable that causes the error:

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

or use the throw statement:

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

Thus, the second method of the subscribe method will be called:

 observable.subscribe( (data) => { (...) }, (err) => { // Will be called in this case } ); 
+3
source

I think that the purest way would be to turn the body of the entire function into an observable, since it will turn any random error into an observable error. Something like that:

 get(endpoint: string): Observable { return Rx.Observable.defer(() => { var headers = new Headers(); this._appendAuthentificationHeaders(headers, this.user.credentials); return Rx.Observable.just(headers); }) .flatMap(headers => this.http.get(endpoint, { headers: headers })) .map(res => res.json()); } 

However, I still disagree that http.get returns an observable instead of a promise. Since these are unambiguous observables, your function can be a simple asynchronous function (sry, js instead of ts):

 async get(endpoint) { var headers = new Headers(); this._appendAuthentificationHeaders(headers, this.user.credentials); const res = await this.http.get(endpoint, { headers })).toPromise(); return res.json(); } 
0
source

Source: https://habr.com/ru/post/1242774/


All Articles