2017-09-04 1 views
2

나는 여러 번 질문을 받았으며 이미 해결책을 찾기 위해 2 시간 이상을 보냈다.Angular 2.0+에서 현재 URL을 얻는 방법

중복 된 질문이나 반복적 인 질문에 대해서는 답하지 마십시오.

나의 현재 URL은 다음과 같습니다 http://localhost:4200/configuration

아래는 내가 구현하려고 많은 온라인으로 볼 솔루션 중 하나입니다.

export class AppComponent implements OnInit{ 
    title = 'app'; 
    constructor(private router: Router, private activatedRoute: ActivatedRoute) { 

    } 

    ngOnInit() { 
    console.log("On Init"); 
    console.log(this.router.url); 
    console.log(this.activatedRoute.url); 
    //this.router.navigate(['/login']); 
    } 
} 

페이지를 다시로드 할 때 출력이 낮아집니다.

On Init 
\ 

나는 방금 빈 URL을 얻고 있습니다. 내가 빠진 것을 알기가 매우 궁금합니다.

도움 주셔서 감사합니다.

+0

무엇을 출력 하시겠습니까? –

+0

내가/구성을 가져야하지 않아야합니까 ?? –

+0

경로 표시 confguratoin –

답변

2

location.href을 사용하면됩니다. 또 다른 옵션은 '@angular/platform-browser'에서 DOCUMENT을 사용하는 것입니다

import { DOCUMENT } from '@angular/platform-browser'; 

constructor(@Inject(DOCUMENT) private document: any){ 
    console.log(location.pathname); 
    console.log(location.href); 
    console.log(this.document.location.href); 
} 

만 그런 다음 URL에서 "/configuration"를 얻을 location.pathname을 사용합니다.

데모 here.

+0

이것은 자바 스크립트입니다. 각도로이 작업을 수행 할 방법이 없습니까? –

+1

이것은 각도입니다. 데모 보셨습니까? – Faisal

+1

해킹의 종류. 나는 배터 방법으로 그것을했지만 내일 사무실에서 한 번 참조하십시오 –

0

이 "/ 구성"

import { Router, NavigationEnd } from '@angular/router'; 
import { isPlatformBrowser } from '@angular/common'; 

.... 

constructor(
    private router: Router, 
.... 

ngOnInit() { 
    if (isPlatformBrowser) { 
     this.router.events 
     .filter(event => event instanceof NavigationEnd) 
     .subscribe(() => { 
      console.log(this.router.routerState.snapshot.url); 
     }) 
    } 
    } 
0

당신은 속성을 제대로 액세스를 제공 할 것입니다. 그러나 설정되기 전에 액세스하고 있습니다. 참조 :

https://stackblitz.com/edit/angular-8phmvc

하면 브라우저가 당신이 설정이있는 각 구성 요소의 수명주기의 어느 부분을 볼 수있는 로그를 확인합니다.

짧은 이야기지만, ngOnInit 대신 ngAfterViewChecked를 시도하거나 라우터를 사용하여 현재 위치를 구독하는 다른 방법을 찾으십시오.

관련 문제