代码之家  ›  专栏  ›  技术社区  ›  rahs

Angular 5中服务的生命周期是什么

  •  50
  • rahs  · 技术社区  · 6 年前

    角度5

    服务是在什么时候创建和销毁的,它的生命周期挂钩(如果有)是什么,它的数据是如何在组件之间共享的?

    编辑 :为了澄清,这是 关于组件生命周期的问题。这个问题是关于服务的生命周期的。如果服务没有生命周期,如何管理组件和服务之间的数据流?

    3 回复  |  直到 6 年前
        1
  •  80
  •   Anuj Yanis-git    5 年前

    服务可以有2个作用域。

    如果在您的模块上声明了服务,那么您将为所有人共享相同的实例,这意味着将在创建第一个需要它的组件/指令/服务/管道时构建服务。然后,当模块本身被销毁时,它将被销毁(大多数情况下,当页面被卸载时)

    如果服务是在组件/指令/管道上声明的,那么每次创建组件/指令/管道时将创建一个实例,而销毁相关组件/指令/管道时将销毁一个实例。

    You can see it in action

    代码测试:2个服务用于显示它们的创建/销毁时间。

    @NgModule({
      providers: [GlobalService] // This means lifeCycle is related to the Module, and only one instance is created for the whole module. It will be created only when the first element who needs it will be created.
    })
    export class AppModule { }
    

    第二个服务是本地组件服务,将为每个 hello-component 实例已创建,并将在 hello组件 将被销毁。

    @Injectable()
    export class LocalService implements OnDestroy{
      constructor() {
        console.log('localService is constructed');
      }
    
      ngOnDestroy() {
        console.log('localService is destroyed');
      }
    }
    
    @Component({
      selector: 'hello',
      template: `<h1>Hello {{name}}!</h1>`,
      styles: [`h1 { font-family: Lato; }`],
      providers: [LocalService]
    })
    export class HelloComponent implements OnInit, OnDestroy {
      @Input() name: string;
    
      constructor(private localService: LocalService, private globalService: GlobalService) {}
    
      ngOnInit(){
        console.log('hello component initialized');
      }
    
      ngOnDestroy() {
        console.log('hello component destroyed');
      }
    }
    

    正如你所见, Service 在角度上可以有 OnDestroy 生命周期挂钩。

        2
  •  3
  •   Fussel    6 年前

    服务只存在于其提供者的范围内,因此存在于模块或单个组件的范围内。它们在第一次注入时被实例化,并且只要提供者存在,就保持活动状态。

    由于服务是普通类,angulars生命周期挂钩不适用于它们。

        3
  •  2
  •   hankchiutw    3 年前

    OnDestroy 适用于官方文件中所述的服务: https://angular.io/api/core/OnDestroy

    报价:

    当指令、管道或服务被销毁时调用的生命周期挂钩。用于销毁实例时需要进行的任何自定义清理。