• 使用服务可以轻松实现跨模块跨组件共享数据,这取决于服务的作用域

    在根注入器中注册服务,所有模块使用同一个服务实例对象

    ```typescript import { Injectable } from ‘@angular/core’;

@Injectable({ providedIn: ‘root’ })

export class CarListService { }

  1. <a name="kl1ZJ"></a>
  2. ### 在模块级别注册服务,该模块中的所有组件使用同一个服务实例对象
  3. - 语法一,新语法
  4. ```typescript
  5. import { Injectable } from '@angular/core';
  6. import { CarModule } from './car.module';
  7. @Injectable({
  8. providedIn: CarModule,
  9. })
  10. export class CarListService { }
  • 语法二,老语法 ```typescript import { CarListService } from ‘./car-list.service’;

@NgModule({ providers: [CarListService], })

export class CarModule { }

  1. <a name="tYone"></a>
  2. ### 在组件级别注册服务,该组件及其子组件使用同一个服务实例对象
  3. ```typescript
  4. import { Component } from '@angular/core';
  5. import { CarListService } from '../car-list.service.ts'
  6. @Component({
  7. selector: 'app-car-list',
  8. templateUrl: './car-list.component.html',
  9. providers: [ CarListService ]
  10. })