如何在angular2应用程序中从url获取路由参数?

如何在angular2应用程序中从url获取路由参数?,angular,Angular,我有一个固定的路线,设置如下: export const ROUTES: Routes = [ { path: 'custom', component: MyCustomComponent } ] 我希望这样,如果用户转到: http://my-angular-app/#/custom/something?mode=CRAZY 在“MyCustomComponent”中,我可以看到访问“mode=CRAZY”并对其进行处理 如何从MyCustomComponent访问变量“mode”

我有一个固定的路线,设置如下:

export const ROUTES: Routes = [
    { path: 'custom', component: MyCustomComponent }
]
我希望这样,如果用户转到:

http://my-angular-app/#/custom/something?mode=CRAZY
在“MyCustomComponent”中,我可以看到访问“mode=CRAZY”并对其进行处理


如何从MyCustomComponent访问变量“mode”?或者我必须定义一个新的路由才能传递参数吗?

这就是我访问组件中的查询参数的方法

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-custom',
  templateUrl: './custom.component.html',
  styleUrls: ['./custom.component.css']
})
export class CustomComponent {

  constructor(private activatedRoute: ActivatedRoute) {
    let mode = activatedRoute.snapshot.queryParams['mode']; //< HERE
    console.log(mode);
  }    
}
从'@angular/core'导入{Component,OnInit};
从'@angular/router'导入{ActivatedRoute};
@组成部分({
选择器:“应用程序自定义”,
templateUrl:“./custom.component.html”,
样式URL:['./custom.component.css']
})
导出类自定义组件{
构造函数(私有activatedRoute:activatedRoute){
让mode=activatedRoute.snapshot.queryParams['mode'];//<此处
console.log(模式);
}    
}
您需要导入
ActivatedRoute
,并通过构造函数注入它。然后,您可以通过注入的服务访问查询字符串中的内容

使用如下路由器链接:

export const ROUTES: Routes = [
    { path: 'custom', component: MyCustomComponent }
]
去那里

控制台日志的输出是疯狂的


希望这能有所帮助。

如其他答案所述,您可以使用
ActivatedRoute.snapshot.queryParam
,但如果您的queryParam在同一路线中更改了它的值,那么如果您需要更新从queryParam获得的值,您将遇到问题。由于您处于同一路径中,因此不会为重新创建组件,因此不会从构造函数中的快照中获取新值。如果在同一路线中需要获取更新的值,则应订阅queryParam observable

constructor(
  private route: ActivatedRoute
) {
  this.route.queryParams.subscribe((queryParams) => {
    console.log(queryParams); // get the values of your queryParams
  });
}

现在,queryParams上的每个新值都将在组件中更新。由于它是一个角度可观测的,您不必费心手动处理它的取消订阅,Angular将为您处理它。

我希望mode:CRAZY在浏览器中成为“可书签”模式。我假设queryParams将其作为post?传递到路由中,因为您在URL中使用哈希,所以您应该能够将这些设置为书签。服务器忽略散列之后的任何内容
queryParams
传递URL上的信息,因此这是一个GET,而不是POST。