Angular 2在其他功能之前运行服务功能

时间:2017-01-04 07:13:07

标签: angular typescript

在AngularJS中,我能够做到这一点:

angular.module('myApp').service('myService', [ function () {   
    this.loadConfiguration = function () {
    };

    this.loadConfiguration();
}]); 

如何在TypeScript中的Angular 2中实现相同的功能,在服务中的其他函数之前调用一个函数?

我试过了:

@Injectable()
export class ChatService {
  ngOnInit() {
      this.loadConfiguration();
  }

  loadConfiguration() {
  }

}

它没有用。

1 个答案:

答案 0 :(得分:5)

注射剂上不存在生命周期钩子。因此,不要在@Injectables中使用@Injectable() export class ChatService { constructor() { this.loadConfiguration(); } loadConfiguration() { } } 之类的生命周期钩子,而是使用构造函数。

{{1}}
  

指令和组件实例具有生命周期,因为Angular会创建,更新和销毁它们。开发人员可以通过在Angular核心库中实现一个或多个Lifecycle Hook接口来利用该生命周期中的关键时刻。

参考:https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html