2016-10-28 7 views
1

私は、ロードされたルートへのアクセス方法を探しています。最初にルート変更で現在のルートをangle2ディレクティブのオプションで取得する方法

は以下のようなルータのイベントで購読することができます。

@Directive({ selector: '[myDirective]' }) 
export class TestDirective { 

    constructor(private _router: Router) { 
     this.doAction() 
    } 


    doAction(): void { 
     this._router.events 
      .filter((event: Event) => event instanceof NavigationEnd) 
      .subscribe(event => { 
       /// ... get current route data 
      }) 
     } 

    } 
} 

主な問題は、どのように)(サブスクライブに現在のルートデータを取得するということです?

角度2の文書で、検索結果が見つかりませんでした。

答えて

2

問題を解決する方法がありますので、こちらを試してください。

import { Router, ActivatedRoute } from '@angular/router'; 

currentRoute:any; 

constructor(private router: Router, private activatedRoute: ActivatedRoute,) {} 


    ngOnInit() { 
    this.router.events.subscribe((url) => { 
     this.currentRoute = url; 
     console.log(this.currentRoute); 
    }); 
    } 

あなたが怒鳴る enter image description here

クエリから値を取得するようにコンソールを取得します。このおqueryParamsにoauth_tokenの値を取得します使用

import { Router, Route, ActivatedRoute } from '@angular/router'; 

queryParams:string; 

constructor(private router: Router, private actRoute: ActivatedRoute) 
{ 
    this.queryParams= 
    this.router.routerState.snapshot.root.queryParams["oauth_token"]; 
} 

をPARMS。私はこれがあなた

NBのための罰金だと思う:あなたのURLは私が(route.data)の値をとりたいhttp://example.com?oauth_token=123

+0

のようになります!あなたの方法はRouter.config()で行い、 "/ login"のような簡単なパスのために返されたオブジェクトの検索を得ることができますが、 "/ heroes /:id"や "/ posts /:"のようなオプションのパラメータでurlを解析するのは難しいです。 post_id/comments /:comment_id " –

+0

クエリパラメータriteを取得する必要がありますか? K回答を更新します –

+0

いいえ!例えば、私は "hasHeader"という名前のルート設定でデータを渡したいと思います:(true | false)、次に、ロードされたルートからこのデータを取得する必要がある各経路変更のディレクティブで!クエリのパラメータがうまくいかない! –

関連する問題