如何在Angular中获取完整的URL?

3

我的应用程序利用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("位置", window.location.href); - Chandru
编辑以澄清问题 - Zack Lucky
1个回答

6

如果您正在使用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);
  });
});

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

正是我所需要的,应该给我一个值而不是直到浏览器接管才变成空白。我会在确保它有效之后将其标记为答案。 - Zack Lucky
David,我复制粘贴了你的代码,并仅将template替换为'./src/index.html'。之后我遇到了这个错误,应用程序无法运行:选择器“app-root”没有匹配任何元素。 - user7747472
@user7747472,“document” 属性必须是 “index.html” 文件的 HTML 内容,而不是路径。我已经编辑了我的回答。 - David
@David,哦,好的,我明白了。这个DIST_FOLDER是一个魔法函数还是常量?对不起,我对Angular很菜。 - user7747472
谢谢David的帮助,终于搞定了。 :) - user7747472

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接