Javascript 实例化 Injectable 类时未调用 ngOnInit

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35110690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:17:33  来源:igfitidea点击:

ngOnInit not being called when Injectable class is Instantiated

javascriptangulartypescript

提问by Levi Fuller

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

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

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

回答by Sasxa

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

生命周期钩子,就像OnInit()使用指令和组件一样。它们不适用于其他类型,例如您的服务。从文档:

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.

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

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

回答by SBD580

I don't know about all the lifecycle hooks, but as for destruction, ngOnDestroyactually get called on Injectable when it's provider is destroyed (for example an Injectable supplied by a component).

我不知道所有的生命周期钩子,但至于销毁,ngOnDestroy当它的提供者被销毁时,实际上会在 Injectable 上被调用(例如一个由组件提供的 Injectable)。

From the docs :

来自 docs :

Lifecycle hook that is called when a directive, pipe or serviceis destroyed.

当指令、管道或服务被销毁时调用的生命周期钩子。

Just in case anyone is interested in destructioncheck thisquestion:

以防万一有人对破坏感兴趣,请检查这个问题:

回答by AJ Richardson

Note: this answer applies only to Angular components and directives, NOT services.

注意:此答案仅适用于 Angular 组件和指令,不适用于服务。

I had this same issue when ngOnInit(and other lifecycle hooks) were not firing for my components, and most searches led me here.

ngOnInit(和其他生命周期钩子)没有为我的组件触发时,我遇到了同样的问题,并且大多数搜索将我带到这里。

The issue is that I was using the arrow function syntax (=>) like this:

问题是我使用了这样的箭头函数语法 ( =>):

class MyComponent implements OnInit {
    // Bad: do not use arrow function
    public ngOnInit = () => {
        console.log("ngOnInit");
    }
}

Apparently that does not work in Angular 6. Using non-arrow function syntax fixes the issue:

显然这在 Angular 6 中不起作用。使用非箭头函数语法解决了这个问题:

class MyComponent implements OnInit {
    public ngOnInit() {
        console.log("ngOnInit");
    }
}

回答by Eduardo A EDUARDO Fernandez Di

I had to call a function once my dataService was initialized, instead, I called it inside the constructor, that worked for me.

一旦我的 dataService 被初始化,我就必须调用一个函数,相反,我在构造函数中调用了它,这对我有用。

回答by HSN KH

import {Injectable, OnInit} from 'angular2/core';
import { RestApiService, RestRequest } from './rest-api.service';
import {Service} from "path/to/service/";

@Injectable()
export class MovieDbService implements OnInit {

userId:number=null;

constructor(private _movieDbRest: RestApiService,
            private instanceMyService : Service ){

   // do evreything like OnInit just on services

   this._movieDbRest.callAnyMethod();

   this.userId = this.instanceMyService.getUserId()


}