patternjavascriptangularCritical
ngOnInit not being called when Injectable class is Instantiated
Viewed 0 times
calledclassbeinginstantiatedinjectablewhennotngoninit
Problem
Why isn't
Code
Console Output
ngOnInit() called when an Injectable class is resolved?Code
import {Injectable, OnInit} from 'angular2/core';
import { RestApiService, RestRequest } from './rest-api.service';
@Injectable()
export class MovieDbService implements OnInit {
constructor(private _movieDbRest: RestApiService){
window.console.log('FROM constructor()');
}
ngOnInit() {
window.console.log('FROM ngOnInit()');
}
}Console Output
FROM constructor()Solution
Lifecycle hooks, like
A Component has a lifecycle managed by Angular itself. Angular creates it, renders it, creates and renders its children, checks it when its data-bound properties change and destroy it before removing it from the DOM.
Directive and component instances have a lifecycle as Angular creates, updates, and destroys them.
OnInit() work with Directives and Components. They do not work with other types, like a service in your case. From docs:A Component has a lifecycle managed by Angular itself. Angular creates it, renders it, creates and renders its children, checks it when its data-bound properties change and destroy it before removing it from the DOM.
Directive and component instances have a lifecycle as Angular creates, updates, and destroys them.
Context
Stack Overflow Q#35110690, score: 452
Revisions (0)
No revisions yet.