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

问题描述 投票:14回答:3

Angular 5

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

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

angular lifecycle angular-services
3个回答
21
投票

服务可以有2个范围。

如果在模块上声明了service,则为所有人共享相同的实例,这意味着将在创建需要它的第一个组件/ directive / service / Pipe时构建服务。然后它将在模块本身被销毁时被销毁(大多数时候页面被卸载)

如果在Component / Directive / Pipe上声明服务,则每次创建Component / Directive / Pipe时都会创建1个实例,并在销毁相关的Component / Directive / Pipe时销毁。

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-component被销毁之前销毁。

@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生命周期钩。


0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.