如何处理 angular 中的查询参数 2

How to handle query parameters in angular 2

在我的 routable component 我有

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

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

根据 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');
   }
}

为了补充前面两个答案,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)。相反 angular 路由器使用所谓的矩阵 URL 表示法。

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

The optional route parameters are not separated by "?" and "&" as they would be in the URL query string. They are separated by semicolons ";" This is matrix URL notation — something you may not have seen before.

似乎 RouteParams 不存在了,取而代之的是 ActivatedRoute. ActivatedRoute gives us access to the matrix URL notation Parameters. If we want to get Query string ? paramaters we need to use Router.RouterState. The traditional 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();
    }
  }
}

我们应该能够在导航时操纵 ? 表示法,以及 ; 表示法,但我只让矩阵表示法起作用。 plnker that is attached to the latest router documentation 显示它应该是这样的。

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

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

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 是文档

(仅适用于儿童路线,例如 /hello-world)

如果您想拨打这种电话:

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

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

/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

这对我有用(截至 Angular 2.1.0):

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

}

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

Angular 4:

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

.html

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

在上面我使用了 link 参数数组 请参阅下面的资源以获取更多信息。

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']))
 }

更多信息:

"Link 参数数组" https://angular.io/docs/ts/latest/guide/router.html#!#link-parameters-array

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

对于Angular4

Url:

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);
     }); 
  }
}

控制台输出:

companyId : 100

Angular 5+更新

The route.snapshot provides the initial value of the route parameter map. You can access the parameters directly without subscribing or adding observable operators. It's much simpler to write and read:

引自Angular Docs

为您分解,以下是使用新路由器的方法:

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

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

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

}

在Angular6中,我找到了这个更简单的方法:

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

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

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

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

在你的 ?-routing.module.ts

中定义一个路径
{ path: '/yourpage', component: component-name }

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

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

将 ActivateRoute 订阅到 ngOnInit

ngOnInit() {

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

提供给 link:

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