Dan*_*ski 0 typescript angular
在AngularJS中,我能够做到这一点:
angular.module('myApp').service('myService', [ function () {
this.loadConfiguration = function () {
};
this.loadConfiguration();
}]);
Run Code Online (Sandbox Code Playgroud)
如何在TypeScript中的Angular 2中实现同样的功能,在服务中的其他函数之前调用一个函数?
我试过了:
@Injectable()
export class ChatService {
ngOnInit() {
this.loadConfiguration();
}
loadConfiguration() {
}
}
Run Code Online (Sandbox Code Playgroud)
它不起作用.
注射剂上不存在生命周期钩子.因此,不要使用像ngOnInitin 这样的生命周期钩子@Injectables,而是使用构造函数.
@Injectable()
export class ChatService {
constructor() {
this.loadConfiguration();
}
loadConfiguration() {
}
}
Run Code Online (Sandbox Code Playgroud)
指令和组件实例具有生命周期,因为Angular会创建,更新和销毁它们.开发人员可以通过在Angular核心库中实现一个或多个Lifecycle Hook接口来利用该生命周期中的关键时刻.
参考:https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html
| 归档时间: |
|
| 查看次数: |
671 次 |
| 最近记录: |