Search code examples
javascriptangularjsrestangular

Using Restangular with the same URL but different files


I need to communicate with a REST web service via Angular and I'm using RestAngular but I'm running into some difficulty. I have to use the same URL but GET & POST to two different files. I'm setting the base URL in my .config in the app.js and the service.js is where I'm setting the other URL via RestangularConfigurer. The BaseURL in the config has a query string appended to it. The second URL in the service does not. I want to GET from the BaseURL in the config and POST to the Factory from an input. Below is an example of my code

app.js

'use strict';

angular
.module('testApp', [
  'ngAnimate',
  'ngCookies',
  'ngResource',
  'ngRoute',
  'ngSanitize',
  'ngTouch',
  'ui.bootstrap',
  'ngGrid',
  'google-maps',
  'ngMessages',
  'restangular'
])
.config(function (RestangularProvider, $routeProvider) {

  RestangularProvider.setBaseUrl('http://dev.domain.com:9005/question-ws.htm?&areacode=215');

  $routeProvider
    .when('/', {
      templateUrl: 'views/main.html',
      controller: 'MainCtrl'
    })

});

service.js

'use strict';

angular.module('testApp')
  .factory('NextRestangular', function($http, $sce, Restangular){
    return Restangular.withConfig(function(RestangularConfigurer) {
      RestangularConfigurer.setBaseUrl('http://dev.domain.com:9005/next-question-ws.htm');
    });
  });
  

controller.js

'use strict';

angular.module('testApp')
  .controller('ScreenCtrl', function ($scope, Restangular, NextRestangular) {

    Restangular.all().getList();

    NextRestangular.all().getList();

  });
  

I can't seem to GET from Restangular and I can't POST to NextRestangular. Will the file structure be able to support this? Am I going about this all wrong?


Solution

  • Restangular is a service to handle Rest API Restful Resources.

    The .htm in your URLs leads me to believe the response is not JSON. I don't believe Restangular will work for you if that is the case. I recommend looking into ngResource or even $http. If your response is JSON, the following should help get you on your way.

    In this example, the baseUrl should be "http://dev.domain.com:9005".

    RestangularProvider.setBaseUrl('http://dev.domain.com:9005');
    

    I have not used setRequestSuffix before but that may allow you to also have the .htm.

    RestangularProvider.setRequestSuffix('.htm');
    

    Then your API calls should look something like this.

    Restangular.all('next-question-ws').get({areacode: 215});
    Restangular.all('next-question-ws').post(
      // JSON Payload here.
    });