Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

254
Visualizações
Obtener la URL actual en Angular

¿Cómo puedo obtener la URL actual en Angular 4? Lo he buscado mucho en la web, pero no puedo encontrar la solución.

aplicación.módulo.ts

 import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule, Router } from '@angular/Router'; import { AppComponent } from './app.component'; import { TestComponent } from './test/test.component'; import { OtherComponent } from './other/other.component'; import { UnitComponent } from './unit/unit.component'; @NgModule ({ declarations: [ AppComponent, TestComponent, OtherComponent, UnitComponent ], imports: [ BrowserModule, RouterModule.forRoot([ { path: 'test', component: TestComponent }, { path: 'unit', component: UnitComponent }, { path: 'other', component: OtherComponent } ]), ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }

aplicación.componente.html

 <!-- The content below is only a placeholder and can be replaced --> <div> <h1>Welcome to {{title}}!!</h1> <ul> <li> <a routerLink="/test">Test</a> </li> <li> <a routerLink="/unit">Unit</a> </li> <li> <a routerLink="/other">Other</a> </li> </ul> </div> <br/> <router-outlet></router-outlet>

aplicación.componente.ts

 import { Component} from '@angular/core'; @Component ({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent{ title = 'Angular JS 4'; arr = ['abcd','xyz','pqrs']; }

otro.componente.ts

 import { Component, OnInit } from '@angular/core'; import { Location } from '@angular/common'; import { Router } from '@angular/router'; @Component({ selector: 'app-other', templateUrl: './other.component.html', styleUrls: ['./other.component.css'] }) export class OtherComponent implements OnInit { public href: string = ""; url: string = "asdf"; constructor(private router : Router) {} ngOnInit() { this.href = this.router.url; console.log(this.router.url); } }

prueba.componente.ts

 import { Component, OnInit } from '@angular/core'; import { Location } from '@angular/common'; import { Router } from '@angular/router'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { route: string; currentURL=''; constructor() { this.currentURL = window.location.href; } ngOnInit() { } }

En este momento tengo un problema con la consola después de hacer clic en otro enlace

 ERROR Error: Uncaught (in promise): Error: No provider for Router!
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Con JavaScript puro:

console.log(window.location.href)

Usando Angular:

this.router.url

 import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Component({ template: 'The href is: {{href}}' /* Other component settings */ }) export class Component { public href: string = ""; constructor(private router: Router) {} ngOnInit() { this.href = this.router.url; console.log(this.router.url); } }

El plunkr está aquí: https://plnkr.co/edit/0x3pCOKwFjAGRxC4hZMy?p=preview

over 4 years ago · Santiago Trujillo Relatório

0

Puede hacer uso del servicio de ubicación disponible en @angular/common y, a través de este código a continuación, puede obtener la ubicación o la URL actual

 import { Component, OnInit } from '@angular/core'; import { Location } from '@angular/common'; import { Router } from '@angular/router'; @Component({ selector: 'app-top-nav', templateUrl: './top-nav.component.html', styleUrls: ['./top-nav.component.scss'] }) export class TopNavComponent implements OnInit { route: string; constructor(location: Location, router: Router) { router.events.subscribe((val) => { if(location.path() != ''){ this.route = location.path(); } else { this.route = 'Home' } }); } ngOnInit() { } }

aquí está el enlace de referencia desde donde he copiado para obtener la ubicación de mi proyecto. https://github.com/elliotforbes/angular-2-admin/blob/master/src/app/common/top-nav/top-nav.component.ts

over 4 years ago · Santiago Trujillo Relatório

0

otro.componente.ts

Así que la solución final correcta es:

 import { Component, OnInit } from '@angular/core'; import { Location } from '@angular/common'; import { Router } from '@angular/router'; /* 'router' it must be in small case */ @Component({ selector: 'app-other', templateUrl: './other.component.html', styleUrls: ['./other.component.css'] }) export class OtherComponent implements OnInit { public href: string = ""; url: string = "asdf"; constructor(private router : Router) {} // make variable private so that it would be accessible through out the component ngOnInit() { this.href = this.router.url; console.log(this.router.url); } }
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda