无法从我的 controller/constructor 访问输入

Cannot access Inputs from my controller/constructor

我有一个带有 @Input 的简单 Angular 2 组件,我将其绑定到模板。模板显示输入数据,但我无法从构造函数访问它:

import {Component, View, bootstrap, Input} from 'angular2/angular2';
import DataService from './data-service';

@Component({
    selector: 'app-cmp'
})
@View({
    template: `{{data.firstName}} {{data.lastName}}` //-> shows the correct 'data'
})
export default class NamesComponent {
  @Input() data: any;
  constructor(dataService: DataService) {
    console.log(this.data);//undefined
  }
}

这是一个 plunker 示例(参见 "names-component.ts")。

我做错了什么?

因为 Input 属性 在设置视图之前不会初始化。根据 docs,您可以在 ngOnInit 方法中访问您的数据。

import {Component, bootstrap, Input, OnInit} from '@angular/core';
import DataService from './data-service';

@Component({
    selector: 'app-cmp',
    template: `{{data.firstName}} {{data.lastName}} {{name}}`
})
export default class NamesComponent implements OnInit {
  @Input() data;
  name: string;
  constructor(dataService: DataService) {
    this.name = dataService.concatNames("a", "b");
    console.log(this.data); // undefined here
  }
  ngOnInit() {
    console.log(this.data); // object here
  }
}

您必须实施 OnChanges,见下文:

import {Component, bootstrap, Input, OnChanges} from '@angular/core';
import DataService from './data-service';

@Component({
    selector: 'app-cmp',
    template: `{{data.firstName}} {{data.lastName}} {{name}}`
})
export default class NamesComponent implements OnChanges {
  @Input() data;
  name: string;
  constructor(dataService: DataService) {
    this.name = dataService.concatNames("a", "b");
    console.log(this.data); // undefined here
  }
  ngOnChanges() {
    console.log(this.data); // object here
  }
}

The way to access your data per documentation here就是写一个setter和一个getter。在这些方法中,您可以操纵 object/data。看这里:

  private _data = '';

  @Input()
  set data(data: any) {
    this._data = data;
  }

  get data(): string { 
    console.log(_data) // <-------- you will see your data here
    return this._data; 
  }
}