2017-06-29 33 views
0

这个问题已经被问,但我已经试过到目前为止似乎无法正常工作角得到queryParameter

ActivatedRoute.queryParams is undefined

Get route query params

我triing找回我的网址的可选查询参数。如果我们假设我的网址是:localhost:4200/site;query=value,我想检索值value

template html

<div> 
     <button type="submit" (click)="query()">Se connecter</button> 
    </div> 

component

import {ActivatedRoute} from "@angular/router"; 
... 
query(): void { 
this.queryDebug = this.activatedRoute.queryParams.subscribe(params => {console.log("params: " + JSON.stringify(params))}); 
} 

我有{}console.log的结果,而我期待value。有什么我失踪?

回答

0

从您的网址localhost:4200/site;query=value看起来像query是可选param而不是queryParamAngular Doc

可选的路由参数没有用“?”号分隔,和“&”,因为它们 将位于URL查询字符串中。它们用分号隔开“;” 这是矩阵URL符号

所以,你可能必须尝试使用​​从文档this.activatedRoute.params

query(): void { 
this.queryDebug = this.activatedRoute.params.subscribe(params => {console.log("params: " + JSON.stringify(params))}); 

范例检索:

localhost:3000/heroes;id=15;foo=foo

ngOnInit() { 
    this.heroes = this.route.params 
     .switchMap((params: Params) => { 
     this.selectedId = +params['id']; 
     return this.service.getHeroes(); 
     }); 
    } 
+0

我想你的建议,但它没有工作。我仍然用控制台得到空的输出。我尝试了两个网址'localhost:4200/site; query = value'和'localhost:4200/site?query = value',但没有得到我期待的内容,即我的'console.log'输出中的值'value' – edkeveked

+0

我刚刚发现我的代码中没有错误。我认为,如果我更改网址并单击该按钮,角度会立即将变化考虑在内;那是我的错误。我必须在浏览器的地址栏中输入,以考虑URL中的更改。我的代码适用于网址'localhost:4200/site; query = value'和'localhost:4200/site?query = value' – edkeveked