通过使用实例绑定方法实现 ngOnInit() 钩子,但它停止工作......
简化示例:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: '<h1>Hello {{name}}</h1>'
})
export class AppComponent {
name = 'Angular';
ngOnInit = () => {
this.name = 'World';
}
}
预期结果=>“Hello World”
真实结果=>“Hello Angular”
是否在某处描述了这些方法不允许完全用于钩子?或者这样使用它们有什么问题?
实例:https://plnkr.co/edit/aZ1CYkDn06KUENmDW3a3?p=preview https://plnkr.co/edit/aZ1CYkDn06KUENmDW3a3?p=preview
重要的:问题不是如何解决。我知道我可以改为ngOnInit() {}
。问题是 -为什么实例绑定方法不能作为钩子使用
跟进在 Angular 存储库中创建了一个问题 - 改进行为/文档/错误通知:https://github.com/angular/angular/issues/16478 https://github.com/angular/angular/issues/16478估计会有更明确的答案。在明确/确认行为是通过设计仅检查类原型后,将在此处发布。
它应该是
ngOnInit() {
this.name = 'World';
}
想象一下你正在覆盖默认循环
固定插头:https://plnkr.co/edit/DGkNulwYs4WpYULhl9gD?p=preview https://plnkr.co/edit/DGkNulwYs4WpYULhl9gD?p=preview
Note:
正如文档中所述,实现生命周期挂钩是可选的。因为javascript没有接口
Source: https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#interface-可选 https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#interface-optional
Edit:
您所做的只是在组件内创建一个名为的函数ngOnInit
如果你想执行它,你必须在组件内的某个地方执行它。最好的地方似乎是构造函数:
constructor(){
this.ngOnInit();
}
固定插头:https://plnkr.co/edit/NAHX5vfoMXtN95Y0oyOR?p=preview https://plnkr.co/edit/NAHX5vfoMXtN95Y0oyOR?p=preview
Edit2:
这是原型的证明:
With the way you do it, the function will not be a part of the prototype chain of the component base class (line 17):
But this way Angular will see it as a part of the prototype chain (line 15):
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)