Daniel Stradowski
Daniel Stradowski

Reputation: 3484

Angular 2 run service function before other functions

In AngularJS I was able to do this:

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

    this.loadConfiguration();
}]); 

How do I achieve the same thing, call one function before others in a service, in Angular 2 in TypeScript?

I tried:

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

  loadConfiguration() {
  }

}

And it doesn't work.

Upvotes: 0

Views: 1638

Answers (1)

eko
eko

Reputation: 40647

Life-cycle hooks doesn't exist on injectables. So instead of using life-cycle hooks like ngOnInit in @Injectables, use the constructor.

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

  loadConfiguration() {
  }

}

Directive and component instances have a lifecycle as Angular creates, updates, and destroys them. Developers can tap into key moments in that lifecycle by implementing one or more of the Lifecycle Hook interfaces in the Angular core library.

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

Upvotes: 5

Related Questions