0

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.

2
  • 2
    Have you tried to call it in constructor? There are no angular2 hooks for regular class Commented Jan 4, 2017 at 7:14
  • 2
    try constructor() Commented Jan 4, 2017 at 7:14

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

@DanielStradowski do you mean like everytime you inject this injectable, you want this constructor to run?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.