问题描述
使用实例绑定方法实现了ngOnInit()挂钩,并停止了工作....
简化示例:
从'@ angular/core'导入{组件};@零件({选择器:"my-app",模板:< h1>您好{{name}}</h1>"})导出类AppComponent {name ='Angular';ngOnInit =()=>{this.name ='世界';}}
预期结果=>"Hello World"实际结果=>"Hello Angular"
是否在某个地方描述了不允许将方法完全用于钩子的地方?还是原样使用它们是什么问题?
实时示例:
但是通过这种方式,Angular会将其视为原型链的一部分(第15行):
Implemented ngOnInit() hook by using instance bound method and it stoped working....
Simplified example:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: '<h1>Hello {{name}}</h1>'
})
export class AppComponent {
name = 'Angular';
ngOnInit = () => {
this.name = 'World';
}
}
expected result => "Hello World"real result => "Hello Angular"
Is it described somewhere that exactly that methods are disallowed to be used exactly for hooks? Or what is the problem w/ using them as such?
Live example: https://plnkr.co/edit/aZ1CYkDn06KUENmDW3a3?p=preview
IMPORTANT: Question is not how to fix. I know that i could change to ngOnInit() {}
. The question is - why instance bound method does not work as a hook
FOLLOW UP Created an issue in the Angular repo - to improve behavior / docs / error notifications: https://github.com/angular/angular/issues/16478 guess there will be more clear answer. Will post it here after it will be clear / confirmed that behavior is by design checking the class prototypes only.
It should be
ngOnInit() {
this.name = 'World';
}
Think of it like you are overriding the default cycle
Fixed plunker: https://plnkr.co/edit/DGkNulwYs4WpYULhl9gD?p=preview
Note:
Implementing the life-cycle hooks are optional as it says in the documentation. Because javascript doesn't have interfaces
Source: https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#interface-optional
Edit:
What you are doing is just creating a function inside your component which is named ngOnInit
if you want to execute it you have to do it somewhere inside your component. The best place to do it seems like the constructor:
constructor(){
this.ngOnInit();
}
Fixed plunker: https://plnkr.co/edit/NAHX5vfoMXtN95Y0oyOR?p=preview
Edit2:
Here's the proof of the prototype:
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):
这篇关于Angular2实例绑定方法不能用作钩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!