1
votes

Comment obtenir l'URL de base avec le chemin dans Angular 5?

Mon URL actuelle est http: // localhost: 4200 / myApp / dashboard .

Je souhaite imprimer l'URL de base, c'est-à-dire http: // localhost: 4200 / myApp à l'aide des fonctionnalités angular 5. P >

J'utilise ce code:

constructor(private platformLocation: PlatformLocation) {
}

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

mais il ne renvoie que le nom de domaine http: // localhost: 4200


3 commentaires

avez-vous essayé: window.location.href


oui, il renvoie aussi le domaine racine


avez-vous essayé this.router.url;


4 Réponses :


2
votes

Vous pouvez injecter Router depuis @ angular / router et utiliser this.router.url

La baseHref devrait être disponible en utilisant this.router.location._baseHref


0 commentaires

3
votes

Vous pouvez également utiliser Location :

import:

const pathAfterDomainName = this.location.path();

Injecter:

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

Utiliser:

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


0 commentaires

0
votes

Ajout de la valeur base_href dans les fournisseurs de modules d'application

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

constructor(private locationStrategy: LocationStrategy) {}
const appPath = location.origin + this.locationStrategy.getBaseHref();

et dans le code

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

providers: [
    { provide: APP_BASE_HREF, useValue: "http://localhost:4500/MyApp" }
]

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


1 commentaires

cette partie je cherchais this.locationStrategy.getBaseHref ()



0
votes

Une autre solution:

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

}


0 commentaires