如何在 Angular 中获取完整的 url? [英] How to get full url in Angular?

查看:49
本文介绍了如何在 Angular 中获取完整的 url?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序利用了 Angular Universal,我想在 Angular 组件中获取当前 url 的完整路径.我想我必须在我可能需要注入窗口的地方使用 window 对象,或者更好的选择是简单地检查它是否在浏览器中.是否有使用 Angular 的 API 的更简洁的解决方案?

My app takes advantage of Angular Universal and I'd like to get the full path of the current url in an Angular component. I think I have to use the window object where I may need to inject the window or maybe the better option is to simply check if it's in the browser. Are there any cleaner solutions utilizing Angular's API?

  url: string;

  constructor(private router: Router) { }

  ngOnInit() {
    this.router.events.subscribe((val) => {
      this.url = `${window.location.protocol}//${window.location.host}${window.location.pathname}`;
    });
  }

我要问的问题是如何以符合 Angular Universal 的方式获取完整的 url

The question I'm asking is how to get the full url in a way that is compliant with Angular Universal

推荐答案

如果你使用的是 Express,你可以将 express 的 url 注入到你的组件中

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

第 1 步:修改您的节点服务器以传递您想要的 url

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);
  });
});

第 2 步:在您的组件/服务中,添加一个可选参数

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

这篇关于如何在 Angular 中获取完整的 url?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆