Home > Software engineering >  Http get returns an HTML page but reads it as text instead of document
Http get returns an HTML page but reads it as text instead of document

Time:09-24

I use HttpClient to call a GET method frop an API that returns a whole HTML page. Until now i just added a parameter "responseType" and gave it the value "document". recently i updated my angular cli version and now the response type can only be one of the followings:

  1. text
  2. json
  3. arraybuffer
  4. blob

neither of the above is the right type, i get the whole page as a very long string. How to i make the http request to read the result as an html? or how i can i convert a string to an html document, where i can call methods like "getElementById" and such

CodePudding user response:

I think this post will help you.In this post,blob was used for converting text to html file.

function dataToHtml(data) {
let html = `
<html>
  <head>
    <meta charset="UTF-8">
    <title>${data.some.value}</title>
  </head>
  <body>
    <h1>${data.some.otherValue}</h1>
    <hr />
    ${data.array.map((thing) => thing.nestedHtml).join("")}
  </body>
</html>`;
const blob = new Blob([html], { type: "text/html" });
const blobUrl = URL.createObjectURL(blob);
window.open(blobUrl, "_blank");
};

CodePudding user response:

If you want to convert a string to an HTML object, maybe this will help: converting a javascript string to a html object

  • Related