javascript - Angular2 将函数结果传递给子组件 - "this.bar is not a function"

标签 javascript angular typescript

我正在尝试将一个函数数据传递给一个 child ,但是关于 SO 的所有答案都来自 Angular2 in (alfa/beta),我不知道我的问题是否来自于官方发布以来事情已经发生了变化发布。我已经尝试了关于 SO 的所有答案,但它似乎并没有消除我的错误,即“this.bar 不是一个函数”

现在我只是想通过函数传递一个简单的字符串:

父组件:

export class ParentComponent implements OnInit {
 foo() {
    return "This is a parent func stream value";
  }
}

父 HTML

<child [bar]="foo()"></child>

子组件

export class ChildComponent implements OnInit {
@Input() bar : Function;

ngOnInit() {
  this.bar();
}

我看不出问题,请帮我看看!

编辑

上面代码中的“Function”类型在我的编辑器中仍然是白色的,这让我很困扰,但是当我像下面的例子一样将代码粘贴到我的组件下面时,相同的“Function”就会变成蓝色,就像我的代码中还有其他类型,所以我想弄清楚为什么会这样……

子组件

export class ChildComponent implements OnInit {
@Input() bar : Function;  //The word "Function" here is white when it should be blue

ngOnInit() {
  this.bar();
}
}

@Input() bar: Function // This word "Function" is blue like it should be
  functionResult: any;
  ngOnInit() {
    this.functionResult = this.bar();
  }

最佳答案

foo()真的不是一个功能。它评估函数调用的返回值。您的输入bar期望一个函数作为它的类型。

你应该尝试像<child [bar]="foo"></child>那样做

编辑
参见 working plunker

关于javascript - Angular2 将函数结果传递给子组件 - "this.bar is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42114896/

相关文章:

javascript - 防止 useEffect 在初始渲染时触发

javascript - jQuery - 通配符选择器以/字符串开头,以/变量结尾

javascript - Onmouse 事件未触发

javascript - Angular 5 : Hide/Show yAxis in Highcharts based on the data

angular - [at-loader] node_modules\@types\jasmine 中的错误

typescript - 类方法不起作用 Angular 2 Typescript

javascript - 在 TypeScript 2.0 中正确使用 React.Events?

javascript - 在 angular.js 中,我可以在 $eval() 之前过滤一些东西吗?

JavaScript 数组和循环

reactjs - 使用 TS : "Property ' __REDUX_DEVTOOLS_EXTENSION_COMPOSE_ _' does not exist on type ' Window'. 的 Redux DevTools 扩展出错?