0

I have some code which works for me in it's current format but I would like to change it so it uses angular httpClient instead.

Here is the current code:

const xhr = new XMLHttpRequest();
const xml = XMLData;
xhr.open('PUT', 'my url here', true);
xhr.setRequestHeader('Content-type', 'text/xml');
xhr.send(xml);
const response = xhr.responseText;

How can I do this with Angular 5's httpClient PUT?

1

1 Answer 1

1

This is what an PUT request with HttpClient and options could look like. You will need to transform your XMLData, whatever that may be, to a string. The SO question provided by @Vikas in his comment mentions a few libraries that are effective at parsing XML.

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class AppService {
  constructor(private http: HttpClient) { }

  doPut() {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'text/xml'
      })
    };

    const xml: string = '<foo>1</foo>';

    return this.http.put("/some/url", xml, httpOptions)
      .subscribe(result => console.log(result));
  }
}

Consolidated version if you prefer:

doPut(xml: string) {    
  return this.http.put("/some/url", xml, { headers: new HttpHeaders({ 'Content-Type': 'text/xml' }) })
    .subscribe(result => console.log(result));
}

The HTTP request will NOT execute unless you subscribe() to the returned Observable produced by put() somewhere. I'd additionally review the documentation for error handling and additional options/functionality.

Hopefully that helps!

Sign up to request clarification or add additional context in comments.

3 Comments

Can't I put the const and subscribe bit inside the doPut() function?
This is a simplified example. Usually you'd simply return this.http.put("/some/url", xml, httpOptions) which returns an Observable and subscribe in something like @Component that injects this service and calls the doPut() method of the service. You can arrange this any way you'd need. This was more to show the PUT using HttpClient at the most basic level.
I should clarify that this does NOT need to be called in an @Injectable. HttpClient can be injected into effectively any @Injectable or @Component. You could execute the put() of an HttpClient instance anywhere you need, it does not need to be in a method called doPut(). This is showing how to create/add headers such as Content-Type, executing the request, and reading the results. Does that help clarify?