加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

dependency-injection – angular2中服务的生命周期方法

发布时间:2020-12-17 07:59:23 所属栏目:安全 来源:网络整理
导读:参见英文答案 ngOnInit not being called when Injectable class is Instantiated3个 是否可以为使用@Injectable()注释的服务提供生命周期挂钩? 我曾经期望在这样的服务上调用生命周期钩子,但我被证明是错误的,它似乎只在@Component上工作.当依赖注入创建/
参见英文答案 > ngOnInit not being called when Injectable class is Instantiated3个
是否可以为使用@Injectable()注释的服务提供生命周期挂钩?

我曾经期望在这样的服务上调用生命周期钩子,但我被证明是错误的,它似乎只在@Component上工作.当依赖注入创建/销毁服务时,有没有办法在服务中获得信息?

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 }
}
注入只是普通类(普通对象),因此它们没有特殊的生命周期.

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读