angular - 无法从我的 Controller /构造函数访问输入

标签 angular typescript

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

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 属性在设置 View 之前不会被初始化。根据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
  }
}

关于angular - 无法从我的 Controller /构造函数访问输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33561845/

相关文章:

mysql - Typeorm 插入数据,即使它存在

javascript - 带有 vue-class-component : next function does not accept callback option 的 Vue 路由器

typescript - 通过Play商店实现付款集成的Ionic应用

angular - 如何从 ionic 选择选项中获取值

angular - ng extract-i18n 配置忽略重复消息

javascript - 在 Angular2 中使用 Parse 作为模块

angular - 在 Angular 6 指令中格式化数字/货币

javascript - 如何为 typescript 命名空间中的函数编写中间件

javascript - Angular 传递标签名称

javascript - Angular 2 : What does binding event to 0 mean?