Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

javascript - 实例化Injectable类时未调用ngOnInit(ngOnInit not being called when Injectable class is Instantiated)

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

(解析Injectable类时,为什么不ngOnInit() ?)

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()
  ask by Levi Fuller translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Lifecycle hooks , like OnInit() work with Directives and Components.

(生命周期挂钩 (例如OnInit()与指令和组件一起使用。)

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本身管理。)

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会创建,渲染,创建和渲染其子级,在其数据绑定属性更改时对其进行检查,并在将其从DOM中删除之前销毁它。)

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

(指令实例和组件实例具有生命周期,因为Angular创建,更新和销毁它们。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...