从angular2

时间:2016-09-23 09:23:43

标签: angular angular2-routing params

使用routerLink导航到另一个组件时,我很难从查询字符串中获取数据。在angular.io的dokumentation之后做了,所以我不确定是什么问题。

组件1:

此组件包含routerLink,如下所示:

<div class="column small-12 large-8 gutter-xsmall-up end waiting">
     Could not find the movie, please go <a [routerLink]="['/request']" [queryParams]="{id:MovieFromImdb.Id, title: MovieFromImdb.Title}">request it</a>
</div>

这会产生这个网址:

http://localhost:3000/request?id=tt0117500&title=The%20Rock

组件2:

在这个组件中,我需要检索数据,但是在使用console.log时它只是保持未定义。

这是我尝试过的。

import { Component } from '@angular/core';
import { AppState } from '../app.service';
import { Params, ActivatedRoute } from '@angular/router';

export class Request {

    private typeArray: Array<any>;
    private defaultSelection: number;
    private Title: string;
    private Link: string;

    constructor(public requestService: RequestService, private route:  ActivatedRoute,) {
        this.defaultSelection = 2;
        this.typeArray = requestService.createList();
    }

    requestMovie(title, link, quality) {
         console.log(title, link, quality);


    }

    ngOnInit() {

        this.route.params.forEach((params: Params) => {
            this.Title = params['title'];
            this.Link = params['id'];

        });

        console.log(this.route.snapshot.params['id'])
        console.log(this.route.snapshot.params['title'])

     }

}

在这里可以看到我做错了吗?

使用最新的 angular2版本。

2 个答案:

答案 0 :(得分:2)

这很简单,您应该使用queryParams代替params

ngOnInit() {

    this.route.queryParams.forEach((params: Params) => {
        this.Title = params['title'];
        this.Link = params['id'];

    });

    console.log(this.route.snapshot.queryParams['id'])
    console.log(this.route.snapshot.queryParams['title'])

 }

https://angular.io/docs/ts/latest/api/router/index/ActivatedRoute-interface.html#!#queryParams-anchor

答案 1 :(得分:1)

你可以像这样使用订阅路线参数: -

ngOnInit() {
      this.route.params.subscribe(params => {
           for(let param in params ) {
                console.log(param, "the param");
           }
      });
}