kb2600
kb2600

Reputation: 11

How to get the Base URL including the context for the storefront?

How to get the Base URL including the context for the storefront?

For example, for this 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

How do I get just

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

Upvotes: 1

Views: 1001

Answers (1)

Krzysztof Platis
Krzysztof Platis

Reputation: 1221

You can get separately the origin (https://s(...).com) and the context URL parameters (electronics-spa/en/USD/).

The origin

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

Note: it won't work in Server Side Rendering! Please use Spartacus' injection token SERVER_REQUEST_ORIGIN then:

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

The context URL parameters

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

Final result

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

Upvotes: 1

Related Questions