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
4 Réponses :
Vous pouvez injecter Router
depuis @ angular / router
et utiliser this.router.url
La baseHref devrait être disponible en utilisant this.router.location._baseHref
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';
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
cette partie je cherchais this.locationStrategy.getBaseHref ()
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()}` } }
avez-vous essayé: window.location.href
oui, il renvoie aussi le domaine racine
avez-vous essayé this.router.url;