简体   繁体   中英

AngularJS - Dynamic URL with ID

config.js

angular.module('config', []).constant('ENV',
    {
        name: 'My Angular Project',
        apiEndPoint: 'http://SOMEIP/myServer', //API host,
        adminUrl:'/admin/regionid/site/siteid/admin/regionid', //endpoint
        loginUrl:'/login/regionid/site/siteid/device'

    });

controller.js

this.userLogin = function(username, password) {

var adminServicePath = ENV.apiEndPoint + ENV.adminUrl
//final url = http://SOMEIP/myServer/admin/1/site/1/admin/1

var loginServicePath = ENV.apiEndPoint + ENV.loginUrl
//final url = http://SOMEIP/myServer/login/2/site/2/device


return $http({
            method: 'POST',
            url: adminServicePath,
            headers: {                       
                "Authorization": "Basic ",
                "Content-Type": "application/x-www-form-urlencoded"
                }
        })

};

Here I am appending API with endpoint to form a complete URL. My issue is regiondid and siteid are dynamic. After user logs in, one REST API request will fetch siteid and regionid in response.

  • How do I dynamically replace siteid and regionid in URL with ID's received in API response? After receiving id's in response, call a function that replaces the value.

You can use the String.prototype.replace(substr, newsubstr)

You can keep regionID instead of ?

 var ENV = { name: 'My Angular Project', apiEndPoint: 'http://SOMEIP/myServer', //API host, adminUrl: '/admin/?/site/?/admin/?', //endpoint loginUrl: '/login/?/site/?/device' }; var adminServicePath = ENV.apiEndPoint + ENV.adminUrl.replace("?", 1).replace("?", 1).replace("?", 1); console.log("Final url admin : " + adminServicePath); var loginServicePath = ENV.apiEndPoint + ENV.loginUrl.replace("?", 2).replace("?", 2); console.log("Final url login : " + loginServicePath); 

I'll assume that the siteid and the regionid can only be obtained from the response to the login endpoint.

Using a constant might not be the best idea here for obvious reasons (ie they're constant, and can't be created at the time you want to create them).

Instead, you could do one of a few things - a simple solution that probably works for a lot of use cases would be to create a login service that wraps your API call and then sets a value either in the service or another service that can be injected into wherever you need it.

It might look like this:

angular.module('app')
  .service('loginService', function($http) {
    var siteId,
        regionId;

    function login(username, password) {
      return $http({
        method: 'POST',
        url: '<login endpoint here>',
        headers: {                       
          "Authorization": "Basic ",
          "Content-Type": "application/x-www-form-urlencoded"
        }
      })
      .then(function(result) {
        siteId = result.siteId;
        regionId = result.regionId;
      });
    }
  ); 

This makes the values available to you any time you need to make an API call after logging in. However, this isn't great since you will need to inject the loginService into any controller/service that needs it, and that controller/service might not really care about the login service at all.

An improved approach to this could be to have an API service that performs the http gets/sets/puts/posts/whatever and that is accessed by your data access layer. Inside this service, you can set/get the siteid and regionid .

It might look like this:

angular.module('app')
  .service('api', function($http) {
     var siteId,
         regionId;

     var defaultHeaders = {
       "Authorization": "Basic ",
       "Content-Type": "application/x-www-form-urlencoded"
     };

     function post(url, options) {
       return $http({
         method: 'POST',
         url: url,
         headers: options.headers ? options.headers : defaultHeaders
       });
     }

     // Other functions to perform HTTP verbs...
  });

angular.module('app')
  .service('loginService', function(api) {
    function login(username, password) {

      api.post('urlHere', options)
        .then(function(result) {
          api.siteId = result.siteId;
          api.regionId = result.siteId;
        });
    }
  });

You can then access the siteid and regionid where you like.

For example:

angular.module('app')
  .controller('someService', function(api) {
    function doSomethingWithTheApi() {
      var url = 'www.google.com/' + api.siteId + '/' + api.regionId + 'whatever-else';
      return api.post(url, {});
    }
  );

Note: the code above isn't complete, but it gives you a very good idea of the approach you could take that is reasonably clean, not too hacky and is easily testable :)

Hope that helps!

instead of constant, you can use value.

angular.module('config', []).value('ENV',
    {
        name: 'My Angular Project',
        apiEndPoint: '', //API host,
        adminUrl:'', //endpoint
        loginUrl:''

    });

Inject ENV and set all values after API call.

ENV.name = xyz;
ENV.apiEndPoint = xyz;
ENV.adminUrl = xyz;
ENV.loginUrl = xyz;

but the values might get set to default once you refresh the browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM