2016-08-10 39 views
1

如何在Angular 2 RC4中獲取查詢參數?我試了文檔,他們沒有任何意義。如何在Angular 2 RC4中獲取查詢參數

例如

http://localhost:3000/models/initials/mid_c1e1c31e6eff42f1982af4124a823b36?test=4 

ngOnInit我怎麼獲取參數test的價值?

private sub: Subscription; 
ngOnInit() { 

    this.sub = this.route.params.subscribe(params => { 

     console.log(params); 
     let id = params['test']; 
     console.log(id); 

    }); 

} 

這是我如何定位到我想要得到的查詢PARMS路線:

this._router.navigate(['models/initials/'+model_id+'?test=4']); 

回答

3
constructor(private route:ActivatedRoute) {} 

ngOnInit() { 
     this.route.params.map(params => params['test']) 
      .subscribe(id => { /* do what you want with the id */ }); 
+0

我得到的,當我做未定義{/ *你想要做什麼用id * /執行console.log(ID)} – Tampa

+0

@Tampa你可以調試並查看你的route.params包含了什麼? – Terje

+0

我的網址看起來像我發佈的內容。如果我更改爲params ['id'],我會獲得mid_c1e1c31e6eff42f1982af4124a823b36,以便部分工作。我只是不能得到?test = 4。看看那個route.param對象,儘管存在於URL窗口中,但我沒有看到它。 – Tampa

-1

你試過RouteSegment

routerOnActivate(curr: RouteSegment) { 
    this.userName = curr.getParam('userName'); 
    this.projId = curr.getParam('projId'); 
    } 
0

你必須使用ActivatedRoute:

private sub: Subscription; 


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

ngOnInit() { 
    this.sub = this.activatedRoute.params.subscribe(
     (param: any) => this.test = param['test'] 
) 
} 
4

OP詢問查詢參數,正確的方法是使用queryParams對象關閉路由。

ngOnInit() { 
    this.sub = this.route.queryParams.subscribe(params => { 
    console.log(params); 
    let id = params['test']; 
    console.log(id); 
}) 
} 

這與其他答案引用的params對象不同。

我還建議使用NavigationExtras對象正確添加到查詢字符串中:https://angular.io/docs/ts/latest/guide/router.html在「查詢參數和片段」部分。

-1

可以通過這種方式它使用JavaScript來實現:

(new URL(location)).searchParams.get("parameter_name") 
相關問題