What is the best way to store URLs or URL domains in an AngularJS application?

The My AngularJS application makes calls to an API that is currently hosted on one service but previously hosted on another, and is likely to be hosted somewhere else in the near future.

The url is constantly changing. For example, from

myfirst.heroku.com/app/user/mike/profile 

to

 mysecond.bluemix.com/app/user/mike/profile 

and etc.

Instead of changing the URL in every place every time, I want to just change the part to /app...

In an Angular app, the best way to do this?

NOTE. . Many of the URLs that I use throughout the application are in modules, which are added as dependencies to my main application. Therefore, Module1 and Module2 use URLs in their controllers and resources and then are included in MainApp . Therefore, a good solution for me should be available for all dependent applications. Is it possible.

+6
source share
3 answers

I would suggest that you should use the angular constant, which is similar to a service, but it creates a constant value that can be implemented everywhere in our angular project.

Here's how we can create a permanent

Continuous Service:

 angular.module('AppName') .constant('REST_END_POINT', 'https://rest.domain.com/'); 

Use in the controller:

 angular.module('AppName') .controller('CTRL_NAME', ['REST_END_POINT', '$scope', function(REST_END_POINT, $scope){ //your business logic. ]); 
+12
source

I am using intercept request for this

 csapp.factory('MyHttpInterceptor', [function () { var requestInterceptor = function (config) { var prefix = "http://api.example.com"; if (config.url.indexOf("/api/") !== -1) { config.url = prefix + config.url; } } }]); 

configure this hook in app.config as

 csapp.config(["$httpProvider", function($httpProvider) { $httpProvider.interceptors.push('MyHttpInterceptor'); }); 

now all your api requests will have the api.example.com prefix.

0
source

$ location.host () is the prefix.domain.suffix clientโ€™s browser. You can enter $ location in any area or service.

 angular.module('app',[]).run(function($rootScope, $location){ $rootScope.host = $location.host(); }) 

Plunk: http://plnkr.co/edit/gDgrlwZFyWNKUJgbHHKj?p=preview

 <!DOCTYPE html> <html ng-app="app"> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js"></script> </head> <body> <i>Host:</i> <h1>{{host}}</h1> <script> angular.module('app',[]).run(function($rootScope, $location){ $rootScope.host = $location.host(); }); </script> </body> </html> 
0
source

Source: https://habr.com/ru/post/980403/


All Articles