angular 学习笔记之 服务

Posted on 2019-06-27 09:42  colson.zhao  阅读(120)  评论(0)    收藏  举报

一、创建服务命令(组件和服务在app目录下是并列的)
ng g service my-new-service
创建到指定目录下面
ng g service services/storage

service.ts下封装服务

创建set方法(传过来是数组或者对象用stringify转译成字符串)

setItem(key,value){
    localStorage.setItem(key,json.stringify(value));
}

get方法(set的是字符串 return转译数组对象)

getItem(key){
  return JSON.pase(localStorage.getItem(key));
}

remove方法

removeItem(){
  localStorage.removeItem(key)
}

 

三、app.module.ts 里面引入创建的服务
1.app.module.ts 里面引入创建的服务
import { StorageService } from './services/storage.service';

2. NgModule 里面的providers 里面依赖注入服务

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

四、使用的页面引入服务,注册服务(引入的服务的名字是在service.ts里面定义的类名)

注意路径../

import { StorageService } from '../../services/storage.service'; 
constructor(private storage: StorageService) { }
使用
依赖注入服务 相当于new了一个服务对象 个人理解
constructor( private storage:xxxservice){
   this.storage.setItem('todolist',this.list); 
  this.storage.getItem('todolist',this.list);

}

 

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3