【问题标题】:How to handle query parameters in angular 2如何处理角度2中的查询参数
【发布时间】:2016-04-08 12:56:35
【问题描述】:

在我的routable component 我有

@RouteConfig {
  {path: '/login',   name: 'Login', component: LoginComponent}
}  

但是如果我转到app_url/login?token=1234,如何获取查询参数?

【问题讨论】:

  • Angular 2.1.0 提供了一个现在应该使用的 ActivatedRoute 的 observable。检查我的答案。

标签: javascript jquery angular angular2-routing


【解决方案1】:

RouteParams 现已弃用,所以这里是如何在新路由器中执行此操作。

this.router.navigate(['/login'],{ queryParams: { token:'1234'}})

然后在登录组件中就可以带参数了,

constructor(private route: ActivatedRoute) {}
ngOnInit() {
    // Capture the token  if available
    this.sessionId = this.route.queryParams['token']

}

Here 是文档

【讨论】:

  • 为了让它工作,我必须这样做。route.snapshot.queryParams...
  • 要补充这一点,现在(目前,角度 5)似乎需要参考快照,如果您正在阅读此内容,请确保包含 .snapshot.queryParams 以节省时间并在此处阅读它@ 987654322@ 感谢@LyleRolleman 指出这一点
【解决方案2】:

为了补充前面的两个答案,Angular2 在路由中支持查询参数和路径变量。在@RouteConfig定义中,如果你在路径中定义了参数,Angular2将它们作为路径变量处理,如果没有,则作为查询参数处理。

我们来取样:

@RouteConfig([
  { path: '/:id', component: DetailsComponent, name: 'Details'}
])

如果你这样调用路由器的navigate方法:

this.router.navigate( [
  'Details', { id: 'companyId', param1: 'value1'
}]);

您将拥有以下地址:/companyId?param1=value1。获取参数的方式对于查询参数和路径变量都是相同的。它们的区别在于路径变量可以看作是强制参数,查询参数是可选参数。

希望对你有帮助 蒂埃里

更新:更改路由器 alpha.31 后,http 查询参数不再起作用 (Matrix params #2774)。相反,角度路由器使用所谓的矩阵 URL 表示法。

参考https://angular.io/docs/ts/latest/guide/router.html#!#optional-route-parameters

可选的路由参数不以“?”分隔和“&”,因为他们 将在 URL 查询字符串中。它们用分号“;”隔开 这是矩阵 URL 表示法——您以前可能没有见过。

【讨论】:

  • 我找了好几个小时!但它不是那样工作的,URL 应该像这样/companyId;param1=value1;param2=value2。无论如何,感谢您以正确的方式指出我,如果我是对的,您可以更新您的答案。
  • 我同意 Silcener 的观点。这 ?不起作用,我也必须使用分号。
  • 路由器的最新文档说:“查询字符串参数不再用“?”和“&”分隔。它们用分号 (;) 分隔这是矩阵 URL 表示法... "
  • 我讨厌投反对票,但这个出色的答案需要更新。
  • 为什么他们使用矩阵 URL 表示法以及如何切换回来。这会造成发送包含 /、+ 和 = 符号的参数的问题
【解决方案3】:

RouteParams 好像已经不存在了,取而代之的是ActivatedRouteActivatedRoute 让我们可以访问矩阵 URL 符号参数。如果我们想要获取查询字符串? 参数,我们需要使用Router.RouterStatetraditional query string paramaters 在路由中保持不变,这可能不是预期的结果。现在在路由器 3.0.0-rc.1 中保留片段是可选的。

import { Router, ActivatedRoute } from '@angular/router';
@Component ({...})
export class paramaterDemo {
  private queryParamaterValue: string;
  private matrixParamaterValue: string;
  private querySub: any;
  private matrixSub: any;

  constructor(private router: Router, private route: ActivatedRoute) { }
  ngOnInit() {
    this.router.routerState.snapshot.queryParams["queryParamaterName"];
    this.querySub = this.router.routerState.queryParams.subscribe(queryParams => 
      this.queryParamaterValue = queryParams["queryParameterName"];
    );

    this.route.snapshot.params["matrixParameterName"];
    this.route.params.subscribe(matrixParams =>
      this.matrixParamterValue = matrixParams["matrixParameterName"];
    );
  }

  ngOnDestroy() {
    if (this.querySub) {
      this.querySub.unsubscribe();
    }
    if (this.matrixSub) {
      this.matrixSub.unsubscribe();
    }
  }
}

我们应该能够在导航时操作? 符号以及; 符号,但我只得到了矩阵符号的工作。附加到最新的router documentationplnker 显示它应该是这样的。

let sessionId = 123456789;
let navigationExtras = {
  queryParams: { 'session_id': sessionId },
  fragment: 'anchor'
};

// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);

【讨论】:

  • 感谢这个答案,让传统的查询参数正常工作。矩阵表示法在 Hotmail 中存在问题。如果您需要向用户发送激活链接(带参数),Hotmail 将对分号进行编码,从而破坏 URL。
  • 嗨,Stephen,“传统的查询字符串参数在路由中保持不变”是什么意思,您能给我们举一些例子吗?我没明白,我也阅读了文档,但我仍在为此苦苦挣扎。
  • 假设你通过 http:/someurl/a-route?do-thing=delete-variable 导航到你的页面,然后通过 this.router.navigate(['/login']) 导航你会最终到达 http://someurl/login?do-thing=set-variable。如果你做了 http:/someurl/a-route;do-thing=set-variable 然后导航你最终在 http:/someurl/login
  • 3.0.0-rc.1 (2016-08-09) “默认不再保留查询参数和片段”github.com/angular/angular/blob/master/modules/@angular/router/…
  • “YourComponent”类型上不存在属性“路由器”
【解决方案4】:

这对我有用(从 Angular 2.1.0 开始):

constructor(private route: ActivatedRoute) {}
ngOnInit() {
  // Capture the token  if available
  this.sessionId = this.route.snapshot.queryParams['token']

}

【讨论】:

  • 在我看来,以上所有答案都充满了错误。这是正确的。
【解决方案5】:

(仅限儿童路线,例如 /hello-world)

如果您想拨打这种电话:

/hello-world?foo=bar&fruit=banana

Angular2 不使用 ? 也不使用 & 而是使用 ; 。所以正确的网址应该是:

/hello-world;foo=bar;fruit=banana

并获取这些数据:

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

private foo: string;
private fruit: string;

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

ngOnInit() {
  this.route.params.forEach((params: Params) => {
      this.foo = params['foo'];
      this.fruit = params['fruit'];
  });
  console.log(this.foo, this.fruit); // you should get your parameters here
}

来源:https://angular.io/docs/ts/latest/guide/router.html

【讨论】:

  • Angular2 使用;(矩阵参数语法)作为子路由的查询参数,? 作为根路由的查询参数。
  • 我尝试像这样运行它并在执行 npm start 时得到以下信息:aot/app/app.component.ngfactory.ts(45,30): error TS2346: Supplied parameters do not match调用目标的任何签名。
【解决方案6】:

Angular2 v2.1.0(稳定版):

ActivatedRoute 提供了一个可以订阅的 observable。

  constructor(
     private route: ActivatedRoute
  ) { }

  this.route.params.subscribe(params => {
     let value = params[key];
  });

每次更新路由时都会触发此事件:/home/files/123 -> /home/files/321

【讨论】:

  • 对于角度 4 有点不同,这是 let value = params.key
【解决方案7】:

在 Angular 7+ 中执行此操作的简单方法是:

在你的 ?-routing.module.ts 中定义一个路径

{ path: '/yourpage', component: component-name }

在你的组件中导入 ActivateRoute 和 Router 模块,并在构造函数中注入它们

contructor(private route: ActivateRoute, private router: Router){ ... }

为 ngOnInit 订阅 ActivateRoute

ngOnInit() {

    this.route.queryParams.subscribe(params => {
      console.log(params);
      // {page: '2' }
    })
}

提供给链接:

<a [routerLink]="['/yourpage']" [queryParams]="{ page: 2 }">2</a>

【讨论】:

  • ActivateRoute 应该是ActivatedRoute
【解决方案8】:

Angular 4:

我在下面包含了 JS(用于 OG)和 TS 版本。

.html

<a [routerLink]="['/search', { tag: 'fish' } ]">A link</a>

在上面我使用的是链接参数数组更多信息请参见下面的来源。

routing.js

(function(app) {
    app.routing = ng.router.RouterModule.forRoot([
        { path: '', component: indexComponent },
        { path: 'search', component: searchComponent }
    ]);
})(window.app || (window.app = {}));

searchComponent.js

(function(app) {
    app.searchComponent =
        ng.core.Component({
            selector: 'search',
                templateUrl: 'view/search.html'
            })
            .Class({
                constructor: [ ng.router.Router, ng.router.ActivatedRoute, function(router, activatedRoute) {
                // Pull out the params with activatedRoute...
                console.log(' params', activatedRoute.snapshot.params);
                // Object {tag: "fish"}
            }]
        }
    });
})(window.app || (window.app = {}));

routing.ts(摘录)

const appRoutes: Routes = [
  { path: '', component: IndexComponent },
  { path: 'search', component: SearchComponent }
];
@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
    // other imports here
  ],
  ...
})
export class AppModule { }

searchComponent.ts

import 'rxjs/add/operator/switchMap';
import { OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';

export class SearchComponent implements OnInit {

constructor(
   private route: ActivatedRoute,
   private router: Router
) {}
ngOnInit() {
    this.route.params
      .switchMap((params: Params) => doSomething(params['tag']))
 }

更多信息:

“链接参数数组” https://angular.io/docs/ts/latest/guide/router.html#!#link-parameters-array

“Activated Route - 路线信息的一站式商店”https://angular.io/docs/ts/latest/guide/router.html#!#activated-route

【讨论】:

    【解决方案9】:

    对于 Angular 4

    网址:

    http://example.com/company/100
    

    路由器路径:

    const routes: Routes = [
      { path: 'company/:companyId', component: CompanyDetailsComponent},
    
    ]
    

    组件:

    @Component({
      selector: 'company-details',
      templateUrl: './company.details.component.html',
      styleUrls: ['./company.component.css']
    })
    export class CompanyDetailsComponent{
       companyId: string;
    
       constructor(private router: Router, private route: ActivatedRoute) {
              this.route.params.subscribe(params => {
              this.companyId = params.companyId;
              console.log('companyId :'+this.companyId);
         }); 
      }
    }
    

    控制台输出:

    公司编号:100

    【讨论】:

      【解决方案10】:

      根据Angular2 documentation,您应该使用:

      @RouteConfig([
         {path: '/login/:token', name: 'Login', component: LoginComponent},
      ])
      
      @Component({ template: 'login: {{token}}' })
      class LoginComponent{
         token: string;
         constructor(params: RouteParams) {
            this.token = params.get('token');
         }
      }
      

      【讨论】:

      • 您从文档中误读。 (错误的字段名称)可能想要解决这个问题。
      • 此解决方案使:token 非可选。
      • 该文档链接上的 404
      • 预发布的旧答案。 RouteParams 已弃用(这就是文档为 404 的原因)
      • ActivatedRoute 的文档链接:angular.io/docs/ts/latest/api/router/index/…
      【解决方案11】:

      Angular 5+ 更新

      route.snapshot 提供了路由参数的初始值 地图。您可以直接访问参数而无需订阅或 添加可观察的运算符。写和读要简单得多:

      引用Angular Docs

      为了给您分解,下面是如何使用新路由器:

      this.router.navigate(['/login'], { queryParams: { token:'1234'} });
      

      然后在登录组件中(注意添加了新的.snapshot):

      constructor(private route: ActivatedRoute) {}
      ngOnInit() {
          this.sessionId = this.route.snapshot.queryParams['token']
      
      }
      

      【讨论】:

        【解决方案12】:

        在 Angular 6 中,我发现了这种更简单的方法:

        navigate(["/yourpage", { "someParamName": "paramValue"}]);
        

        然后在构造函数中或者ngInit中可以直接使用:

        let value = this.route.snapshot.params.someParamName;
        

        【讨论】:

          猜你喜欢
          • 2023-03-07
          • 1970-01-01
          • 2011-04-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-20
          • 2015-11-19
          • 2021-11-28
          相关资源
          最近更新 更多