要在Angular Universal中获取当前URL,可以使用Angular提供的PlatformLocation
服务。以下是一个示例代码:
首先,导入所需的模块和服务:
import { Component, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
import { PlatformLocation } from '@angular/common';
然后,在组件的构造函数中注入PlatformLocation
和PLATFORM_ID
:
constructor(
private platformLocation: PlatformLocation,
@Inject(PLATFORM_ID) private platformId: any
) { }
接下来,在组件的ngOnInit
生命周期钩子中根据当前平台执行相应的逻辑:
ngOnInit() {
if (isPlatformBrowser(this.platformId)) {
// 在浏览器端执行的逻辑
const currentUrl = window.location.href;
console.log('Current URL in browser:', currentUrl);
}
if (isPlatformServer(this.platformId)) {
// 在服务器端执行的逻辑
const currentUrl = (this.platformLocation as any).location.href;
console.log('Current URL on server:', currentUrl);
}
}
在浏览器端,可以直接使用window.location.href
获取当前URL。
在服务器端,由于没有window
对象,我们需要使用PlatformLocation
的location
属性来获取当前URL。注意,由于location
属性是protected
,我们需要将其类型转换为any
才能访问href
属性。
以上就是在Angular Universal中获取当前URL的解决方法。根据当前平台(浏览器端或服务器端),我们可以使用不同的方法来获取URL。