我当前的网址是http://localhost:4200/myApp/dashboard。
我想使用角度5功能打印基本URL,即http://localhost:4200/myApp。
我正在使用以下代码:
constructor(private platformLocation: PlatformLocation) {
}
const appPath = (this.platformLocation as any).location.origin
但是它仅返回域名http://localhost:4200
答案 0 :(得分:2)
您可以从Router
注入@angular/router
并使用this.router.url
baseHref应该使用this.router.location._baseHref
答案 1 :(得分:2)
您也可以使用Location:
导入:
import {Location} from '@angular/common';
注入:
constructor(@Inject(Location) private readonly location: Location) {}
使用:
const pathAfterDomainName = this.location.path();
答案 2 :(得分:0)
在应用程序模块提供程序中添加了base_href值
import { APP_BASE_HREF } from '@angular/common';
providers: [
{ provide: APP_BASE_HREF, useValue: "http://localhost:4500/MyApp" }
]
和代码
import { LocationStrategy, Location } from '@angular/common';
constructor(private locationStrategy: LocationStrategy) {}
const appPath = location.origin + this.locationStrategy.getBaseHref();
提琴:https://stackblitz.com/edit/angular-router-basic-example-rqcji3?file=app%2Fapp.component.ts
答案 3 :(得分:0)
其他解决方案:
import { DOCUMENT, LocationStrategy } from '@angular/common';
@Injectable()
export class SomeService {
constructor(@Inject(DOCUMENT) private readonly document: any,
private readonly locationStrategy: LocationStrategy) {}
// for localhost: http://localhost:4200/someBaseHref
getUrl(): string {
return `${this.document.location.origin}/${this.locationStrategy.getBaseHref()}`
}
}