- 使用服务可以轻松实现跨模块跨组件共享数据,这取决于服务的作用域
在根注入器中注册服务,所有模块使用同一个服务实例对象
```typescript import { Injectable } from ‘@angular/core’;
@Injectable({ providedIn: ‘root’ })
export class CarListService { }
<a name="kl1ZJ"></a>### 在模块级别注册服务,该模块中的所有组件使用同一个服务实例对象- 语法一,新语法```typescriptimport { Injectable } from '@angular/core';import { CarModule } from './car.module';@Injectable({providedIn: CarModule,})export class CarListService { }
- 语法二,老语法 ```typescript import { CarListService } from ‘./car-list.service’;
@NgModule({ providers: [CarListService], })
export class CarModule { }
<a name="tYone"></a>### 在组件级别注册服务,该组件及其子组件使用同一个服务实例对象```typescriptimport { Component } from '@angular/core';import { CarListService } from '../car-list.service.ts'@Component({selector: 'app-car-list',templateUrl: './car-list.component.html',providers: [ CarListService ]})
