Is it possible to use RestAngular.setBaseUrl for two api access points?

混江龙づ霸主 提交于 2020-01-22 14:30:08

问题


Is it possible to work with Restangular with 2 different APIs? I would like to have setBaseUrl() for both.


回答1:


just create two or more Restangular service and config them as you want and inject your module which one you want to use...

UPDATE

this code from restangular github page

// Global configuration
app.config(function(RestangularProvider) {
   RestangularProvider.setBaseUrl('http://www.global.com');
   RestangularProvider.setRequestSuffix('.json');
});

//First Restangular Service
app.factory('FirstRestangular', function(Restangular) {
   return Restangular.withConfig(function(RestangularConfigurer) {
      RestangularConfigurer.setBaseUrl('http://www.first.com');
   });
});

//Second Restangular Service
app.factory('SecondRestangular', function(Restangular) {
   return Restangular.withConfig(function(RestangularConfigurer) {
      RestangularConfigurer.setBaseUrl('http://www.second.com');
   });
});

instead of global config (although you can still set global config for shared properties) create Restangular factories like these and inject them your controller...

// Let's use them from a controller
app.controller('MainCtrl', function(Restangular, FirstRestangular, SecondRestangular) {

  // GET to http://www.google.com/users.json
  // Uses global configuration
  Restangular.all('users').getList()

  // GET to http://www.first.com/users.json
  // Uses First configuration which is based on Global one, therefore .json is added.
  FirstRestangular.all('users').getList()

  // GET to http://www.second.com/users.json
  // Uses Second configuration which is based on Global one, therefore .json is added.
  SecondRestangular.all('users').getList()
});



回答2:


@wickY26 has the right answer, but I wanted to add something important.

If you are going to minify your code, you need to use inline annotation like so:

app.factory('FirstRestangular', [ 'Restangular', function(Restangular) {
   return Restangular.withConfig(function(RestangularConfigurer) {
      RestangularConfigurer.setBaseUrl('http://www.first.com');
   });
}]);

Note the square brackets.



来源:https://stackoverflow.com/questions/22274975/is-it-possible-to-use-restangular-setbaseurl-for-two-api-access-points

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!