【Angular】08服务serve

1、概念

把从组件内抽离出来的代码叫服务,服务的本质就是函数

官方认为组件不应该直接获取或保存数据, 它们应该聚焦于展示数据,而把数据访问的职责委托给某个服务。而服务就充当着数据访问,逻辑处理的功能。把组件和服务区分开,以提高模块性和复用性。通过把组件中和视图有关的功能与其他类型的处理分离开,可以让组件类更加精简、高效。

2、使用

命令ng g s serves/list创建一个服务,通过**@Injectable()**装饰器标识服务。

//导入Injectable装饰器
import {
    
     Injectable } from '@angular/core';
//使用Injectable装饰器声明服务
@Injectable({
    
    
  //作用域设定,'root'表示默认注入,注入到AppModule里
  providedIn: 'root'
})
export class ListService {
    
    

  constructor() {
    
     }
  
  list:Array<string>=['Angular','React','Vue']

  getList(){
    
    
    return this.list
  }

  addList(str:string){
    
    
    this.list.push(str)
  }
}

组件中如何使用服务,必须将服务依赖注入系统、组件或者模块,才能够使用服务。用注册提供商根注入器实现。该服务本身是 CLI 创建的一个类,并且加上了 @Injectable() 装饰器。默认情况下,该装饰器是用 providedIn 属性进行配置的,它会为该服务创建一个提供商。

import {
    
     ListService } from '../serves/list.service';

constructor(private listService:ListService) {
    
     }

list:Array<string> | undefined
ngOnInit(): void {
    
    
  console.log('sthome-ngOnInit')
  this.list = this.listService.getList()
}

// 渲染结构
<!-- 服务 -->
<p *ngFor="let item of list">{
    
    {
    
    item}}</p>

猜你喜欢

转载自blog.csdn.net/shentian885/article/details/126329871