Angular学习第六课--服务service的管理

1、服务service: 各组件component中的代码不能供应,如果需要有公用的代码,则使用service组件

//创建到指定目录下面
ng g service services/storage

服务创建完成后,在app.module.ts中会自动生成如下代码:

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

@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
NewsComponent,
TodolistComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [StorageService],
bootstrap: [AppComponent]
})
export class AppModule { }

2、其他组件component中如何使用service

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


//在constructor函数中注册服务
constructor(private storage: StorageService) {
}


//使用服务
addData(){
// alert(this.username);
this.list.push(this.username);
this.storage.set('todolist',this.list);
} r
emoverData(key){
console.log(key);
this.list.splice(key,1);
this.storage.set('todolist',this.list);
}

3、服务中的代码

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

@Injectable({
  providedIn: 'root'
})
export class StorageService {

  constructor() { }

  set(key:string,value:any){

	//浏览器本地存储对象localStorage
    localStorage.setItem(key,JSON.stringify(value));
  }
//从本地存储中依据key获取值localStorage.getItem(key)
//Json对象解析:JSON.parse()
  get(key:string){

    // return 'this is a service';
    return JSON.parse(localStorage.getItem(key))

  }
  //从本地存储中删除对象localStorage.removeItem(key);
  remove(key:string){

    localStorage.removeItem(key);
  }
}

 

你可能感兴趣的:(Angular)