1

I'm trying to implement an app with angular 2 and need to make requests to my API server. However, I think it's a bad idea to hardcode the full URL in every request because it will change very likely. I took a look to this post: Set base url for angular 2 http requests

but that works for beta version. I'm using RC6 and can't make it to work. Any help would be appreciated.

Community
  • 1
  • 1
Javier Enríquez
  • 630
  • 1
  • 9
  • 25

2 Answers2

1

If you run your json backend on the same server which provides your client code - you don't need to specify port in url. For other url settins (like I have all my services under /api/) I use a separate helper class which deals with all configuration and such and this one has /api/ hardcoded, but it's only in that one place. Easy to change either manually or during build process.

The class can be something like that:

export class Configuration {
    private static _apiUrl = "/api";
    private static _childUrl = `${Configuration._apiUrl}/child`;

    public static apiUrl(url: string): string {
        return `${this._apiUrl}/${url}`;
    }

    public static getChildComponentUrl(url: string): string {
        return `${this._childUrl}/${url}`;
    }
}
rook
  • 2,819
  • 4
  • 25
  • 41
0

If you are building your angular app with a build tool like Gulp, you can control the Base URL of your app at build time. It doesn't allow you to switch Base URLs at runtime, but it would allow you to, say, build an app pointed to your local machine or a server with a single command.

gulpfile.js:

var gulpUtil = require('gulp-util');
var gulpData = require('gulp-data');
var gulpTemplate = require('gulp-template');

var sourceDir = 'path/to/src';
var buildDir = 'path/to/build/target';

gulp.task('default', [],
        function() {
            return gulp.src(sourceDir + 'index.html')
                .pipe(gulpData(function() {
                        return {
                            baseUrl : gulpUtil.env.baseUrl
                        };
                    }))
                .pipe(gulpTemplate())
                .pipe(gulp.dest(buildDir));
        });

and then in your index.html:

<script>
    angular.module('myApp', [])
    .provider('appConfigProvider', function () {
      return {
        $get: function () {
          return {
              baseUrl: '<%= baseUrl %>'
          };
        }
      };
    });
</script> 

Then when you run gulp, provide the baseUrl as a command-line argument:

gulp --baseUrl https://my.server.com

This sets an environment variable available inside gulpUtil.env; you can also provide configuration via, say, a props file and gulp-props (though I haven't used it). Configuring angular applications via a single command is one of my favorite uses for taskrunners like Gulp.

Good luck!

Nate Vaughan
  • 3,471
  • 4
  • 29
  • 47