如何在 angular 5 中获取基础 url 和路径?

How to get base url along with path in angular 5?

我目前的 url 是 http://localhost:4200/myApp/dashboard

我想使用 angular 5 个特征打印基础 url,即 http://localhost:4200/myApp

我正在使用此代码:

constructor(private platformLocation: PlatformLocation) {
}

const appPath = (this.platformLocation as any).location.origin

不过它returns只有域名http://localhost:4200

您可以从 @angular/router 注入 Router 并使用 this.router.url

baseHref 应该可以使用 this.router.location._baseHref

您也可以使用 Location:

进口:

import {Location} from '@angular/common';

注入:

constructor(@Inject(Location) private readonly location: Location) {}

使用:

const pathAfterDomainName = this.location.path();

在应用程序模块提供程序中添加了 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();

Fiddle: https://stackblitz.com/edit/angular-router-basic-example-rqcji3?file=app%2Fapp.component.ts

其他一些解决方案:

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()}`
  }

}

试试这个:

import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common';
import {Component, Injector} from '@angular/core';

@Component({
  selector: 'path-location',
  providers: [Location, {provide: LocationStrategy, useClass: PathLocationStrategy}],
  template: `
    <h1>PathLocationStrategy</h1>
    Current URL is: <code>{{myLocation.path()}}</code><br>
    BaseHref is: <code>{{myLocation.getBaseHref()}}</code><br>
  `
})
export class PathLocationComponent {

  public myLocation: LocationStrategy;

  constructor(private injector: Injector) {

    /** Define i18n idioma do sistema */
    this.myLocation= this.injector.get(LocationStrategy);

    console.log('BaseHref: ' + this.myLocation.getBaseHref());
    console.log('Path: ' + this.myLocation.path());
  }
}

基于: https://angular.io/api/common/Location#example

和: https://angular.io/api/common/LocationStrategy