为什么在解析Injectable类时调用ngOnInit()?
码
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()'); } }
控制台输出
FROM constructor()
Lifecycle hooks,像OnInit()与指令和组件一起工作。他们不与其他类型,如在您的情况下的服务工作。来自文档:
原文链接:https://www.f2er.com/angularjs/146066.htmlA 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 destroys it before removing it from the DOM.
Directive and component instances have a lifecycle as Angular creates,updates,and destroys them.