Angular服务

Angular服务的使用

1,创建服务

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

2,使用服务

扫描二维码关注公众号,回复: 10002984 查看本文章
  • 在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(); // 调用服务中的删除本地缓存数据的方法

}

猜你喜欢

转载自www.cnblogs.com/zxuedong/p/12534662.html
今日推荐