Noah
Noah

Reputation: 974

Rendering ERB HTML from Rails to Angular, Angular trying to interpret as JSON

I have the snippet below that sends a custom HTTP request through $resource. The endpoint it hits returns an HTML response from an ERB template in Rails.

JS/Angular:

Case
  .getTemplate({ id: $routeParams.id, template: $scope.template.name })
  .$promise
  .then(function(response) {
    console.log(response);
  });

My goal is to then use that HTML and put it into a textarea. However, the result of logging the response to the console shows JSON like so:

{
  "1": "<",
  "2": "!",
  "3": "d",
  "4": "o",
  "5": "c"
}

The very first characters in the HTML response are <!doctype html>. Angular is splitting up the HTML response, character by character into JSON with the key being an iterator and the value being each character.

How can I prevent it from doing this so I can reference response in the anonymous function and use the HTML returned from the API.

Edit:

function CaseService($resource, BASE) {
  return $resource(BASE + 'cases/:id', {
    id: '@id'
  }, {
    getTemplate: {
      method: 'POST',
      url: BASE + 'cases/:id/get_template',
      headers: {
        'Accept': 'text/html'
      }
    }
  });
}

angular
  .module('MyModule')
  .factory('Case', CaseService);

Upvotes: 0

Views: 409

Answers (1)

caffeinated.tech
caffeinated.tech

Reputation: 6548

Try setting your responseType to an empty string, which may override the default setting of json, as per the MDN doc

function CaseService($resource, BASE) {
  return $resource(BASE + 'cases/:id', {
    id: '@id'
  }, {
    getTemplate: {
    method: 'POST',
    url: BASE + 'cases/:id/get_template',
    headers: {
      Accept: 'text/html'
    },
    responseType: ''  // This is the magic line
  }
 });

This is mentioned in the $resource doc

Upvotes: 1

Related Questions