【问题标题】:How to get full url in Angular?如何在 Angular 中获取完整的网址?
【发布时间】:2018-04-19 08:20:01
【问题描述】:

我的应用程序利用了 Angular Universal,我想在 Angular 组件中获取当前 url 的完整路径。我想我必须使用window 对象,我可能需要在其中注入窗口,或者更好的选择是简单地检查它是否在浏览器中。有没有使用 Angular 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

【问题讨论】:

  • 试试这样:console.log("location", window.location.href);
  • 编辑澄清问题

标签: angular angular-universal


【解决方案1】:

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

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

//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 步:在您的组件/服务中,添加一个可选参数

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

【讨论】:

  • 正是我要找的东西,应该给我一个值,而不是在浏览器接管之前保持空白。一旦我确定它有效,我会标记为答案。
  • 大卫我复制粘贴了你的代码,只用'./src/index.html'替换了template。之后我收到此错误,应用程序将无法运行The selector "app-root" did not match any elements.
  • @user7747472 document 属性必须是 index.html 文件的 html,而不是路径。我编辑了我的答案
  • @David,哦,好吧,我明白了。这个DIST_FOLDER 是一个神奇的函数还是一个常数。对不起,我不喜欢角
  • Ty David 帮了很多忙,终于让它工作了。 :)
猜你喜欢
  • 2018-05-16
  • 1970-01-01
  • 1970-01-01
  • 2017-11-28
  • 2018-09-13
  • 2014-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多