{"id":22903437,"url":"https://github.com/sawyerbutton/service-lifecycle","last_synced_at":"2026-05-16T01:34:56.587Z","repository":{"id":120750738,"uuid":"154430068","full_name":"sawyerbutton/service-lifecycle","owner":"sawyerbutton","description":"Angular service lifecycle demonstration","archived":false,"fork":false,"pushed_at":"2018-10-25T02:21:04.000Z","size":1094,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-02-07T04:40:21.881Z","etag":null,"topics":["angular","lifecycle-management","service"],"latest_commit_sha":null,"homepage":"https://sawyerbutton.github.io/service-lifecycle/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sawyerbutton.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-10-24T02:59:43.000Z","updated_at":"2018-10-25T02:21:05.000Z","dependencies_parsed_at":null,"dependency_job_id":"10e7212d-3c6b-4cf7-af84-7ef3dd2b4906","html_url":"https://github.com/sawyerbutton/service-lifecycle","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sawyerbutton%2Fservice-lifecycle","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sawyerbutton%2Fservice-lifecycle/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sawyerbutton%2Fservice-lifecycle/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sawyerbutton%2Fservice-lifecycle/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sawyerbutton","download_url":"https://codeload.github.com/sawyerbutton/service-lifecycle/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246598895,"owners_count":20803107,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["angular","lifecycle-management","service"],"created_at":"2024-12-14T02:36:42.836Z","updated_at":"2026-05-16T01:34:51.568Z","avatar_url":"https://github.com/sawyerbutton.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ServiceLifecycle\n\n## Angular中服务的生命周期\n\n\u003e Angular官方教程中只提及了生命周期在组件,指令中的应用而并没有提及服务也有其生命周期\n\n\u003e service同样可以实现OnDestroy, OnInit, AfterViewInit, AfterViewChecked, AfterContentChecked, AfterContentInit接口\n\n\u003e 需要注意的是只有`OnDestroy`接口有实际的调用效果\n\n\u003e 也就是说可以通过`constructor`和`OnDestroy`接口实现对service的监控效果\n\n\n### 声明在Module中的Service生命周期\n\n\u003e 如果服务申明于模块之中,模块中的每个部分都将会共享同样的服务实例\n\n\u003e 服务将会在某个时间点被构造出来,而这个时间点和依赖注入了该服务的 `组件/ 指令 / 服务 / 管道` 初次被创建的时间点有关\n  \n\u003e 服务被创建后不会跟随被注入的 `组件/ 指令 / 服务 / 管道`的销毁而被销毁, 而是跟随模块的销毁而销毁\n\n```typescript\n// ...\n@NgModule({\n  declarations: [\n    AppComponent,\n    HelloComponent\n  ],\n  imports: [\n    BrowserModule\n  ],\n  bootstrap: [AppComponent],\n  providers: [GlobalService]\n})\n```\n\n\u003e 需要注意的是,在同步`NgModule` 里面配置的 `provider` 在整个 APP 范围内都是可见的,\n\n\u003e 亦即,即使在某个子模块里面配置的`provider`服务,它们依然是全局可见的,可以被注射到任意类里面\n\n\u003e 更需要注意的是,异步模块里面配置的`providers`只对本模块中的成员可见\n\n\u003e 如果在其他模块里面引用异步模块里面配置的`provider`会产生异常\n\n\u003e 其本质原因是,Angular会给异步加载的模块创建独立的注射器树\n           \n\n\n### 直接声明于更小颗粒中的Service生命周期\n\n\u003e 如果服务直接申明于` 组件 / 指令 / 管道` 中时,服务会在注入的 `组件 / 指令/ 管道`被创建时创建对于的服务实例\n\n\u003e 该实例依存于创被建的 ` 组件 / 指令 / 管道`,并随着` 组件 / 指令 / 管道`的销毁而销毁\n\n```typescript\n// hello.component.ts\n@Component({\n  selector: 'app-hello',\n  templateUrl: './hello.component.html',\n  styleUrls: ['./hello.component.css'],\n  providers: [LocalService]\n})\n```\n\n\u003e 如果将service配置在 `组件 / 指令 / 管道`内部的 `providers` 中,服务奖不再是单例模式了\n\n\u003e 每个`组件 / 指令 / 管道`都拥有自己独立的 UserListService 实例, 其内部的`provider`生命周期与其自身保持一致,这才是service生命周期的关键\n                                                \n\n### Service的注入机制\n\n- 使用组件举例避免`providers`无法插入到`pipe`中的情况,以下组件可以替换为指令进行适配,注入机制同样适用于指令的某些场景\n\n- 如果组件内部配置了`providers`优先使用组件上的配置来创建注入对象,否则向父层组件继续查找,父组件上找不到继续向所属的模块查找,一直查询到根模块 `AppModule` 里面的`providers` 配置\n\n- 最终若未找到指定的服务,则抛出异常\n\n- 同步模块里面配置的 `providers` 是全局可见的,即使是很深的子模块里面配置的 `providers`依然是全局可见的(与深度无关)\n\n- 异步模块里面配置的`providers`只对本模块中的成员可见\n\n- 组件里面配置的 `providers` 对组件自身和所有`子层组件`可见\n\n- `injector`的生命周期与组件自身保持一致,当组件被销毁的时候,对应的`injector`也会被销毁\n\n### @Inject 和 @Injectable\n\n\u003e 与常见的通过`@Injectable`为服务生成元数据之外,也可以通过`@Inject`作为手动挡的方式手动指定元数据类型信息\n\n```typescript\nimport {Inject, Injectable} from '@angular/core';\nimport { UUID } from 'angular2-uuid';\nimport {HttpClient} from '@angular/common/http';\n\nexport class InjectTestService {\n  private _id: string;\n  constructor(\n    @Inject(HttpClient) private http\n  ) {\n    this._id = UUID.UUID();\n  }\n}\n```\n\n\u003e 值得注意的是,用` @Inject` 和用 `@Injectable` 最终编译出来的代码是不一样的\n\n\u003e 用 `@Inject` 生成的代码会多于`@Injectable`导致最后生成的文件变大\n\n#### @Inject的另类用法\n\n\u003e `@Inject`不仅可以注入强类型的对象也可以注入弱类型的对象字面值\n\n```typescript\nimport { Injectable, Inject } from '@angular/core';\nimport {MY_CONFIG_TOKEN} from '../my.config';\n\n// @Injectable({\n//   providedIn: 'root'\n// })\nexport class LiteralService {\n\n  constructor(\n    @Inject(MY_CONFIG_TOKEN) config: object\n  ) {\n    console.log(config);\n  }\n}\n```\n\n\u003e 前提是\n\n```typescript\nimport { InjectionToken} from '@angular/core';\n\nexport const MY_CONFIG = {\n  name: '@Inject标签测试'\n};\n\nexport const MY_CONFIG_TOKEN = new InjectionToken\u003cstring\u003e('my_config.ts');\n```\n\n```typescript\n@NgModule({\n  declarations: [\n    AppComponent,\n    HelloComponent,\n    TestDirective\n  ],\n  imports: [\n    BrowserModule\n  ],\n  bootstrap: [AppComponent],\n  providers: [GlobalService, LiteralService, {provide: MY_CONFIG_TOKEN, useValue: MY_CONFIG}]\n})\n```\n\n\u003e 只是事实上上述方式也可以通过直接将配置文件直接通过`import`引入服务中实现\n\n\u003e 使用上述方式更多的是一种屠龙之术,只是龙在Angular中是存在的\n\n\n### @Self标签\n\n\u003e 对于子组件而言,其可以使用在父组件的层面上定义的服务\n\n![non self tag](./src/assets/angury1.png)\n\n\u003e 由于`SonComponent`嵌套在`FatherComponent`内部,而且其自身没有配置 `providers`\n\u003e 所以其共享了父层的`inject-test-service`实例\n\n\n- 利用`@Self` 装饰器来提示注射器不要向上查找只在组件自身内部查找依赖\n\n\u003e 需要注意的是,使用`@Self`标签后需要注意本组件中是否包含所需依赖`providers`\n\n\u003e 若注射器没有找到相应的依赖则会抛出错误\n\n```typescript\nimport {Component, OnInit, Self} from '@angular/core';\nimport {InjectTestService} from '../../services/inject-test.service';\n\n@Component({\n  selector: 'app-self-son',\n  templateUrl: './self-son.component.html',\n  styleUrls: ['./self-son.component.css'],\n  providers: [InjectTestService]\n})\nexport class SelfSonComponent implements OnInit {\n  id$: any;\n  constructor(\n    @Self() private injectTestService: InjectTestService\n  ) { }\n\n  ngOnInit() {\n    this.id$ = this.injectTestService.getServiceId();\n  }\n}\n```\n\n![self tag](./src/assets/angury2.png)\n\n### @SkipSelf和@Optional\n\n\u003e 见名知意系列之 `@SkipSelf`\n\n\u003e 采用`@SkipSelf`标签将会使注射器跳过组件自身,沿着`injector tree`向上寻找依赖\n\n```typescript\nimport {Component, OnInit, SkipSelf} from '@angular/core';\nimport {InjectTestService} from '../../services/inject-test.service';\n\n@Component({\n  selector: 'app-skip-self-son',\n  templateUrl: './skip-self-son.component.html',\n  styleUrls: ['./skip-self-son.component.css'],\n  providers: [InjectTestService]\n})\nexport class SkipSelfSonComponent implements OnInit {\n  id$: any;\n  constructor(\n    @SkipSelf() private injectTestService: InjectTestService\n  ) { }\n\n  ngOnInit() {\n    this.id$ = this.injectTestService.getServiceId();\n  }\n}\n```\n\n![skip self tag](./src/assets/angury3.png)\n\n\u003e可以组合使用` @SkipSelf `与 `@Optional`\n\n```typescript\n@SkipSelf() @Optional() public injectTestService: InjectTestService\n```\n\n\u003e 使用` @Optional `装饰器后如果在父层上找到了指定的依赖类型则会据此创建实例,否则,直接设置依赖为null并不抛异常(_存疑_)\n\n![skip self optional tag](./src/assets/angury4.png)\n\n## @Host与Content Projection\n\n\u003e Content Projection 的作用是动态指定组件所需要的内容\n\n![skip self tag](./src/assets/angury5.png)\n\n- `@Host`装饰器会提示注射器:在组件自己内部查找需要的依赖或到 `Host（宿主）`上去查找\n\n- 换言之`@Host` 装饰器是`被投影的组件`和`其宿主`之间构建联系的纽带\n\n\u003e 如果宿主上面并没有所需要的依赖时可以使用`@Optional` 装饰器避免程序崩溃(抛出异常不可避)\n\n### Use Injector Manually(待定)\n\n### Providers 和 viewProviders\n\n\u003e 当在component中使用`viewProviders`提供providers时,注入在父组件的服务奖不会注入到通过投影引入的内容\n\n\u003e 如果希望像上述的方式在将注入在父组件的服务同样提供给投影内容，需要使用`Providers`实现\n\n\u003e `viewProviders`的实际作用可以理解为限制`providers`注入只面向子组件而不面向投影组件\n\n\u003e `viewProviders`防止投影内容扰乱服务，其家住在构建angular library时将会得到体现\n\n```typescript\nimport { Component, OnInit } from '@angular/core';\nimport {InjectTestService} from '../../services/inject-test.service';\n\n@Component({\n  selector: 'app-view-provider-father',\n  templateUrl: './view-provider-father.component.html',\n  styleUrls: ['./view-provider-father.component.css'],\n  // viewProviders: [InjectTestService]\n  providers: [InjectTestService]\n})\nexport class ViewProviderFatherComponent implements OnInit {\n  id$: any;\n  constructor(\n    private injectTestService: InjectTestService\n  ) { }\n  ngOnInit() {\n    this.id$ = this.injectTestService.getServiceId();\n  }\n}\n```\n\n\u003e 当是用`viewProviders`属性作为元数据时,投影内容无法获取父组件中的注入的服务，所以会报出`NullInjectorError: NoProvider for InjectTestService!\n\n![view provider bug](./src/assets/bug1.png)\n\n\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsawyerbutton%2Fservice-lifecycle","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsawyerbutton%2Fservice-lifecycle","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsawyerbutton%2Fservice-lifecycle/lists"}