angular - 使用angular2中的参数从url检索数据

标签 angular angular2-routing parameters

在使用 routerLink 导航到另一个组件时,我很难从我的查询字符串中获取数据。在 angular.io 的文档化之后完成,所以我不确定哪里出了问题。

组件 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>

这会产生这个 url:

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 版本。

最佳答案

这很简单,您应该使用 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

关于angular - 使用angular2中的参数从url检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39657202/

相关文章:

Angular Build EPERM : operation not permitted, 复制文件

angular - Google Picker API + Angular2 获取未捕获类型错误 : Cannot read property 'handleAuthResult' of undefined

javascript - 在 setInterval 函数中传递参数

sql - 参数化 SQL IN 子句

angular - Moment() 未在 Angular 中定义

javascript - ExpressionChangedAfterItHasBeenCheckedError : Expression has changed after it was checked using Angular2

javascript - Angular2 中表单控件的非字符串值

angular - 当路径完全匹配 '/' 时如何突出显示?

javascript - routerlink 接受字符串参数

CSS类名参数?