实例化 Injectable 类时未调用 ngOnInit [英] ngOnInit not being called when Injectable class is Instantiated

查看:23
本文介绍了实例化 Injectable 类时未调用 ngOnInit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在解析 Injectable 类时不调用 ngOnInit()?

Why isn't ngOnInit() called when an Injectable class is resolved?

代码

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()

推荐答案

生命周期钩子,如OnInit() 与指令和组件一起工作.它们不适用于其他类型,例如您的服务.来自文档:

Lifecycle hooks, like OnInit() work with Directives and Components. They do not work with other types, like a service in your case. From docs:

组件具有由 Angular 本身管理的生命周期.Angular 创建它,渲染它,创建并渲染它的子节点,在它的数据绑定属性改变时检查它,并在将它从 DOM 中删除之前销毁它.

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.

指令和组件实例在 Angular 创建、更新和销毁它们时具有生命周期.

Directive and component instances have a lifecycle as Angular creates, updates, and destroys them.

这篇关于实例化 Injectable 类时未调用 ngOnInit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆