angular2中服务的生命周期方法 [英] Life-cycle methods for services in angular2

查看:121
本文介绍了angular2中服务的生命周期方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以为使用@Injectable()注释的服务设置生命周期挂钩?

Is it possible to have life-cycle hooks for a service that is annotated with @Injectable()?

我曾希望可以在这样的服务上调用生命周期挂钩,但是事实证明我错了,它似乎仅在@Component上起作用.当依赖项注入创建/破坏服务时,是否可以在服务中获得通知?

I'd have expected the life-cycle hooks to be called on a service like this, but I was proven wrong, it seems to be working on @Component only. Is there a way to get informed in a service when dependency injection creates / destroys a service?

import {Component, Injectable, OnInit, OnDestroy} from 'angular2/core';

@Injectable()
export class SampleService implements OnInit, OnDestroy {
    ngOnInit() {
        console.log("OnInit")
    }
    ngOnDestroy() {
        console.log("OnDestroy")
    }
}

@Component({
  selector: "sample",
  template: "<div>Sample Component</div>",
  providers: [ SampleService ]
})
export class SampleComponent {
  constructor() { private _sampleService: SampleService }
}

推荐答案

可注入对象只是普通类(普通对象),因此它们没有特殊的生命周期.

Injectables are just normal classes (normal objects) and as such, they have no special lifecycle.

在创建您的类的对象时,将调用该类的构造函数,这就是您的"OnInit"的含义.至于销毁,服务并没有真正销毁.唯一可能发生的事情是,一旦不再有对其的引用,就将其收集为垃圾,这很可能是在依赖项注入器本身被删除之后发生的.但是您通常无法控制它,并且JavaScript中没有解构函数的概念.

When an object of your class is created, the class’s constructor is called, so that’s what your "OnInit" would be. As for the destruction, a service does not really get destroyed. The only thing that might happen is that it gets garbage collected once there is no longer a reference to it, which likely happens after the dependency injector is removed itself. But you generally have no control over it, and there is no concept of a deconstructor in JavaScript.

@Injectable()
export class SampleService {
    constructor() {
        console.log('Sample service is created');
    }
}

这篇关于angular2中服务的生命周期方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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