在Angular中添加基本href的完整路径



我想在Angular中获得基本href,包括域(或子域(

用例:

我想使用元服务添加ogg:image属性。当前内容看起来像CCD_ 2,但我希望它是CCD_。

注意:我使用SSR。

我们在app-config.service.ts中做一些相关的事情,在那里URI库将为您解析const { scheme, host, path } = URI.parse(window.location.href);

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { tap, concatMap, catchError } from 'rxjs/operators';
import * as URI from 'uri-js';
import { Observable } from 'rxjs';
import { environment } from '../../../environments/environment';
@Injectable({
providedIn: 'root',
})
export class AppConfigService {
public config?: {} = {};
private env?: {} = {};
constructor(private readonly http: HttpClient) {
this.getHostBase();
}
/**
* Use to get the data found in the second file (config file)
*/
public getConfig(key: any) {
return this.config[key];
}
/**
* Use to get the data found in the first file (env file)
*/
public getEnv(key: any) {
return this.env[key];
}
/**
* This method:
*   a) Loads "env.json" to get the current working environment (e.g.: 'production', 'development')
*   b) Loads "config.[env].json" to get all env's variables (e.g.: 'config.development.json')
*/
public load(): any {        
return new Promise((resolve) => {
this.http
.get('assets/env.json')
.pipe(
catchError((): any => {
resolve(true);
}),
)
.subscribe((envResponse: any) => {
this.env = envResponse;
const request = this.http.get(`assets/config.${envResponse.env}.json`);
if (request !== undefined) {
request
.pipe(
catchError((error: any): any => {
resolve(true);
}),
)
.subscribe((responseData: object) => {
this.config = { ...this.config, ...responseData };
resolve(true);
});
} else {
resolve(true);
}
});
});
}
public get host(): string | undefined {
return this.getConfig('api');
}
private getHostBase(): void {
const { scheme, host, path } = URI.parse(window.location.href);

this.config['host'] = URI.serialize({ scheme, host, path: `${cleanPath}/` });
this.config['api'] = URI.serialize({ scheme, host, path: `${cleanPath}/api/` });

}
}

您可以看到我们在这里构建了最终的URL:const { scheme, host, path } = URI.parse(window.location.href);

您可以使用Document.location.origin:https://developer.mozilla.org/en-US/docs/Web/API/Location-请注意,当使用SRR(而不是仅使用全局document对象(时,必须注入Document Object

代码示例

class UrlService {
constructor(@Inject(DOCUMENT) private document: Document,
private router: Router) {}
getOrigin(): string {
return this.document.location.origin;
}
getPath(): string {
return this.router.url;
}
}

最新更新