无法访问我的控制器/构造函数的输入 [英] Cannot access Inputs from my controller/constructor

查看:55
本文介绍了无法访问我的控制器/构造函数的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple Angular 2 component with @Input, which I bind to the template. The template shows input data, but I cannot access it from the constructor:

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").

Here is a plunker with an example (see "names-component.ts").

我在做什么错了?

推荐答案

因为在设置视图之前,不会初始化Input属性.根据文档,您可以使用ngOnInit方法访问数据.

Because the Input property isn't initialized until view is set up. According to the docs, you can access your data in ngOnInit method.

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

这篇关于无法访问我的控制器/构造函数的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆