如何获取包括店面上下文在内的基本URL?

时间:2020-02-12 13:59:22

标签: spartacus-storefront

如何获取包括店面上下文在内的基本URL?

例如,对于此URL

https://spartacus.c39j2-walkersde1-d4-public.model-t.cc.commerce.ondemand.com/electronics-spa/en/USD/OpenCatalogue/Cameras/Digital-Cameras/Digital-SLR/c/578

我如何得到

https://spartacus.c39j2-walkersde1-d4-public.model-t.cc.commerce.ondemand.com/electronics-spa/en/USD/

1 个答案:

答案 0 :(得分:1)

您可以分别获取来源(https://s(...).com)和上下文URL参数(electronics-spa/en/USD/)。

起源

import { DOCUMENT } from '@angular/common';
// ...
constructor(@Inject(DOCUMENT) private document: any){}
//...
const origin = this.document.location.origin;
// "https://s(...).com"

注意:它在服务器端渲染中不起作用!请然后使用Spartacus的注入令牌SERVER_REQUEST_ORIGIN

import { DOCUMENT } from '@angular/common';
import { PLATFORM_ID } from '@angular/core';
import { SERVER_REQUEST_OTIGIN } from '@spartacus/core';
// ...
constructor(
   @Inject(DOCUMENT) private document: any,
   @Inject(PLATFORM_ID) private platformId,
   @Inject(SERVER_REQUEST_ORIGIN) private serverRequestOrigin
){}
// ...
let origin;
if (isPlatformServer(this.platformId)){
   origin = this.serverRequestOrigin;
} else {
   origin = this.document.location.origin;
}

上下文URL参数

import { Router } from '@angular/router';
// ...
constructor(private router: Router){}
// ...
const context = router.serializeUrl(router.createUrlTree(''));
// "electronics-spa/en/USD/"

最终结果

const result = `${origin}/${context}`;
// "https://s(...).com/electronics-spa/en/USD/"