从URL获取ID,使用Angular2未定义params

时间:2016-07-27 18:19:58

标签: javascript angular params

尝试从URL中获取ID参数,但似乎我没有定义我的params var。无法看到我出错的地方,也许有人可以提供帮助!

代码

import {Component} from 'angular2/core';
import {ROUTER_DIRECTIVES, RouteParams, RouteConfig} from 'angular2/router';
import {OnInit} from 'angular2/core';

@Component({
  selector: 'view-movie',
  templateUrl : './templates/view-movie.tpl.html',
  directives: [ROUTER_DIRECTIVES]
})

export class ViewmovieComponent implements OnInit {

  public movie = {};
  public id = String;

  constructor(params: RouteParams){};

  ngOnInit() {
    this.id = params.get('id');
  }



}

2 个答案:

答案 0 :(得分:0)

假设在构造函数之后的代码块中插入了params.get,如此

import {Component} from 'angular2/core';
import {ROUTER_DIRECTIVES, RouteParams, RouteConfig} from 'angular2/router';
import {OnInit} from 'angular2/core';

@Component({
  selector: 'view-movie',
  templateUrl : './templates/view-movie.tpl.html',
  directives: [ROUTER_DIRECTIVES]
})

export class ViewmovieComponent implements OnInit {

  public movie = {};
  public id = String;

  constructor(params: RouteParams){

    this.id = params.get('id');

  }

  ngOnInit() {
    console.log(this.id);
  }

}

答案 1 :(得分:0)

只需使用这一个

constructor(params: RouteParams){this.id = params.get('id');}

  ngOnInit() {console.log(this.id);}

或者这个

constructor(private params: RouteParams){}

  ngOnInit() {
    this.id = this.params.get('id');
    console.log(this.id);
  }

因为如果我们初始化没有声明类型的东西,那么我们必须在构造函数中访问,但是如果我们要在构造函数之外访问那么必须使用this