Angular服务

Posted on 2020-03-20 20:34  张雪冬前端学习园地  阅读(191)  评论(0编辑  收藏  举报

Angular服务的使用

 

 

1,创建服务

 

  • ng g service 文件夹名/服务名

 

 

 

 

2,使用服务

 

  • 在app.module.ts中引入并声明服务  

 

// 引入服务
import { StorageService } from './services/storage.service'

// 配置服务
@NgModule({
  providers: [StorageService], // 配置项目所需要的服务
})

 

  • 在服务中定义公共的方法  

import { Injectable } from '@angular/core';

@Injectable({

  providedIn: 'root'
})

export class StorageService {

  constructor() { }

// 定义方法

  set() {

    // 存储
    window.localStorage.setItem('变量名', JSON.stringify(变量值));
  }

  get() {

    // 获取
    window.localStorage.getItem('变量名');
  }

  remove() {

    // 删除
    window.localStorage.removeItem('变量名');
  }
}

 

  • 在组件中引入服务并且使用服务中的方法

  

import { StorageService } from '../../services/storage.service'

constructor(public storage: StorageService) {

    this.storage.set(); // 调用服务中的设置本地缓存数据的方法

    this.storage.get(); // 调用服务中的获取本地缓存数据的方法

    this.storage.remove(); // 调用服务中的删除本地缓存数据的方法

}