How to get full url in Angular?

瘦欲@ 提交于 2019-12-08 19:22:39

If you are using Express, you can inject the url from express to your component

Step #1: modify your node server to pass the url you want

//Get index.html file contents from dist/browser/index.html
const DIST_FOLDER = join(process.cwd(), 'dist'); 
const template = readFileSync(join(DIST_FOLDER, 'browser', 'index.html')).toString();


app.engine('html', (_, options, callback) => {
var fullUrl = options.req.protocol + '://' + options.req.get('host') + options.req.originalUrl;

  renderModuleFactory(AppServerModuleNgFactory, {
    // Our index.html
    document: template,
    url: options.req.url,
    // DI so that we can get lazy-loading to work differently (since we need it to just instantly render it)
    extraProviders: [
      provideModuleMap(LAZY_MODULE_MAP),
      {
        provide: 'serverUrl',
        useValue: fullUrl
      }
    ]
  }).then(html => {
    callback(null, html);
  });
});

Step #2: In your component/service, add an optionnal parameter

constructor(@Inject(PLATFORM_ID) private platformId: Object, @Optional() @Inject('serverUrl') protected serverUrl: string)
{
 // Here, this.serverUrl will have a value only when using angular universal
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!