Angular CLI build using base-href and deploy-url to access assets on CDN

To access --deploy-url value at application runtime, create deploy-url.ts with:

export const DEPLOY_URL = new InjectionToken<string>('deployUrl');

And use this snippet in your main.ts file:

const deployUrl = (function() {
  const scripts = document.getElementsByTagName('script');
  const index = scripts.length - 1;
  const mainScript = scripts[index];
  return mainScript.src.replace(/main.*?\.js$/, '');
})();

const DEPLOY_URL_PROVIDER = {
  provide: DEPLOY_URL,
  useValue: deployUrl,
};

platformBrowserDynamic([DEPLOY_URL_PROVIDER])
  .bootstrapModule(AppModule)
  .catch(err => console.error(err));

The idea is to get the url of currently executed Javascript file, which is main.js (or main.hash.js if outputHashing is enabled) and strip filename from it. Then in your services inject --deploy-url value with @Inject(DEPLOY_URL) deployUrl: string as a constructor parameter.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)