Skip to content

10 Service

10.1 Create Service

import { Injectable } from '@angular/core';
@Injectable({
    providedIn: 'root'
})
export class TestService { }
export class AppComponent {
    constructor (private testService: TestService) {}
}

Screenshot 2025-01-18 at 16.23.23

Screenshot 2025-01-18 at 16.23.32

10.2 Service Scopes

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

  1. 在根注入器中注册服务,所有模块使用同一个服务实例对象。
import { Injectable } from '@angular/core';
@Injectable ({
 providedIn:
})
export class CarListService {
}

Screenshot 2025-01-18 at 16.57.52

Screenshot 2025-01-18 at 16.58.01

  1. 在模块级别注册服务,该模块中的所有组件使用同一个服务实例对象。
import { Injectable } from '@angular/core'; 
import { CarModule } from './car module';

@Injectable({
 providedIn: CarModule,
})

export class CarListService{
}
import { CarListService } from './car-list.service'
@NgModule (
 providers: [CarListService],
})
}
export class CarModule {

Screenshot 2025-01-18 at 17.00.12

Screenshot 2025-01-18 at 17.00.18

  1. 在组件级别注册服务,该组件及其子组件使用同一个服务实例对象。
import { Component } from '@angular/core';
import { CarListService } from '../car-list.service.ts
@Component({
  selector:'app-car-list',
  templateUrl: './car-list.component.html',
 providers: [ CarListService ]
})