Angular 2 - 无法从路由器获取URL

时间:2017-03-03 02:21:57

标签: angular angular2-routing

我使用console.log(_router.url)时无法获取网址。它只返回/(斜杠)

当我执行以下代码时:

constructor(
    private el: ElementRef,
    private _auth:AuthenticationService,
    @Inject(AppStore) private store: Store<AppState>,
    private _router:Router,
  ) {

    console.log(_router);
    console.log(_router.url);
  }

这是console.log(_router)的结果 enter image description here

单击(...)时会显示"/languages"

enter image description here

但是当我console.log(_router.url)这只是打印

enter image description here

2 个答案:

答案 0 :(得分:2)

您始终可以尝试从位置服务获取路线

constructor(location: Location) {
  console.log(location.path());
}

Location docs

答案 1 :(得分:2)

@Owain van Brakel的回答是正确的,但遗漏了一些细节,我无法使用this.router.url(如StackOverflow中的其他答案所示)所以我使用了location.path(),结果类似。

这是我的代码:

// This is important because when you use Location in the constructor it
// gets accepted but the wrong library is used. 
import { Location } from '@angular/common';

export class MainComponent {
   constructor(public location: Location) {
      console.log(this.location.path());
   }
}