Marc
Marc

Reputation: 13194

Get Observable<T> from HttpClient.get with options

Usually, I perform a get request using Angular HttpClient like in this example:

this.http
   .get<Project>('/api/projects/' + id)
   .subscribe(p => {
    // p is typed as Project
    this.project = p;
  });

The type parameter Project defines the expected response. HttpCLient.get<T>() returns an Observable<T>.

I now need to add some options to the request, like i.e. so:

getRequestOptions() {
   var headers = new HttpHeaders();
   headers.append('Authorization', 'Basic ' + this.auth.EMail + ':' + this.auth.Token);
   return { headers: this.getRequestOptions() };
}

// Somewhere else   
this.http.get<Project>(url, this.getRequestOptions())
         .subscribe(p => { 
             // p is HttpEvent<Project> with no (direct?) access to the
             // returned object, just a property called type
         });

This calls a different overload of the get() method, which for some reasons return not an Observable<T> but an Observable<HttpEvent<T>>. Apart from that being bad design in my opinion:

How do I use HttpEvent? It only contains one property called type. I am aware that there are derived types, in case of a get request probably HttpResponse<T>. Do I really need to deal with all that type switching and casting stuff, just because I am using RequestOptions?

What is the background of this design decision? Why don' all overloads return the same type and share a common usage pattern?

Upvotes: 1

Views: 2650

Answers (1)

Marc
Marc

Reputation: 13194

There are two things wrong about the code in my question: There is a stack overflow error due to the recursive function call, as Und3rTow pointed out in his comment. Secondly, HttpHeaders is immutable obviously. The append() method returns a new HttpHeaders object but doesn't alter the original one. As an alternative to using the modified object it is possible to pass key value pairs in the constructor. The working code is:

getRequestOptions() {
    var headers = new HttpHeaders({'Authorization' : 'Basic ' + this.auth.EMail + ':' + this.auth.Token});
    var options = {      
      headers: headers 
    };
    return options;
}

Upvotes: 2

Related Questions